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
Use the
lengthPropertyYou can simply use the
lengthproperty 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:
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:
need an explanation for this answer? contact us directly to get an explanation for this answer