#get last element
#access last element
#array
#javascript
#programming

How do i get the last item in an array using javascript?

Anonymous

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:

Using pop() method:

const array = [1, 2, 3, 4, 5];
const lastItem = array.pop();

console.log(lastItem); // Output: 5

Using the slice() method:

const array = [1, 2, 3, 4, 5];
const lastItem = array.slice(-1)[0];

console.log(lastItem); // Output: 5

Using the reduce() method:

const array = [1, 2, 3, 4, 5];
const lastItem = array.reduce((acc, curr) => curr);

console.log(lastItem); // Output: 5

Using the spread operator ... and pop() method:


const array = [1, 2, 3, 4, 5];
const lastItem = [...array].pop();

console.log(lastItem); // Output: 5

Happy Coding  😎