- Using the length property: You can subtract 1 from the length of the array to get the index of the last item, and then access it with brackets notation.
var arr = [1, 2, 3, 4]; var lastItem = arr[arr.length - 1]; // 4
- Using the pop() method: The pop() method removes the last item from the array and returns it. This can be useful if you need to remove the last item anyway.
var arr = [1, 2, 3, 4]; var lastItem = arr.pop(); // 4
Note that using the pop() method changes the array itself.
- Using the slice() method: The slice() method can be used to create a new array with a subset of the original array. You can use a negative index to start from the end of the array, and set the end index to undefined to include all elements from the starting index to the end of the array.
var arr = [1, 2, 3, 4]; var lastItem = arr.slice(-1); // 4
This creates a new array with the last element and then access it with brackets notation.