AnonymousJan 09, 2024
To get the last item in an array in JavaScript, you can use the index -1
to access the last element.
Here's an example:
const array = [1, 2, 3, 4, 5];
const lastItem = array[array.length - 1];
console.log(lastItem); // Output: 5
In this example, we have an array array with elements [1, 2, 3, 4, 5]
. We can use array.length -1
as the index to access the last element, which is 5. The value of lastItem will be 5, and it will be printed to the console.
Here are a few different methods you can use to get the last item in an array in JavaScript, along with examples:
pop()
method:const array = [1, 2, 3, 4, 5];
const lastItem = array.pop();
console.log(lastItem); // Output: 5
slice()
method:const array = [1, 2, 3, 4, 5];
const lastItem = array.slice(-1)[0];
console.log(lastItem); // Output: 5
reduce()
method:const array = [1, 2, 3, 4, 5];
const lastItem = array.reduce((acc, curr) => curr);
console.log(lastItem); // Output: 5
spread operator ... and pop()
method:
const array = [1, 2, 3, 4, 5];
const lastItem = [...array].pop();
console.log(lastItem); // Output: 5