Please note, this is a STATIC archive of website www.tutorialrepublic.com from 10 Sep 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

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:

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:

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:

Advertisements
Bootstrap UI Design Templates