PASSWORD RESET

Your destination for complete Tech news

How to get the last item in an array?

490 0
< 1 min read

To get the last item in an array in JavaScript, you can use the length property of the array to access the last element. The length property returns the number of elements in the array, so to get the last element, you can use the following syntax:

let myArray = ['a', 'b', 'c', 'd'];
let lastItem = myArray[myArray.length - 1];
console.log(lastItem); // 'd'

Alternatively, you can use the pop() method, which removes the last element from the array and returns it. This method modifies the original array, so be aware that it will change the size of the array. Here’s an example:

let myArray = ['a', 'b', 'c', 'd'];
let lastItem = myArray.pop();
console.log(lastItem); // 'd'
console.log(myArray); // ['a', 'b', 'c']

If you do not want to modify the original array, you can use the slice() method to create a new array containing only the last element. Here’s an example:

let myArray = ['a', 'b', 'c', 'd'];
let lastItem = myArray.slice(-1)[0];
console.log(lastItem); // 'd'
console.log(myArray); // ['a', 'b', 'c', 'd']

Which method you choose will depend on your specific needs and the environment in which you are working.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.