How to Get the Last Item in an Array in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the length
Property
You can simply use the length
property to select or get the last item in an array in JavaScript. This is the fastest and most cross-browser compatible solution.
Let's take a look at an example to understand how it basically works:
Example
Try this code »var fruits = ["Apple", "Banana", "Kiwi", "Mango", "Orange"];
// Accessing the last item
var last = fruits[fruits.length - 1];
console.log(last); // Prints: Orange
You can alternatively use the slice()
method to extract the last element from a JavaScript array without modifying the original array. Let's check out an example:
Example
Try this code »var fruits = ["Apple", "Banana", "Kiwi", "Mango", "Orange"];
// Extracting the last item
var last = fruits.slice(-1)[0];
console.log(last); // Prints: Orange
Related FAQ
Here are some more FAQ related to this topic: