Q:

How to Get the Last Item in an Array in JavaScript

0

How to Get the Last Item in an Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the Current Date in JavaScript... >>
<< How to Trigger a Button Click on Enter Key Press i...