To get the last element in an array in JavaScript, you can use array indexing with the length property.
In this example,
numbers
with some elements.numbers[numbers.length - 1]
and store it in the variable lastNumber
.lastNumber
to the console.const numbers = [1, 2, 3, 4, 5];
const lastNumber = numbers[numbers.length - 1];
console.log('Last number is:', lastNumber);
Last number is: 5
In this example,
fruits
with some elements.fruits[fruits.length - 1]
and store it in the variable lastFruit
.lastFruit
to the console.const fruits = ['apple', 'banana', 'cherry'];
const lastFruit = fruits[fruits.length - 1];
console.log('Last fruit is:', lastFruit);
Last fruit is: cherry
In this tutorial, we learned How to get Last Element in Array in JavaScript language with well detailed examples.