JavaScript get last element of an array Example; In this tutorial you will learn how to get the last Element of an Array in JavaScript;
In Js we have different methods to get last element (item) from an array like array.length, array pop, array slice etc.
Example 1: Using array length Method
To get the last element of an array in JavaScript we can get array.length and then – 1. The calculation evaluates to the index of the last element in the array.
const arr = ['a', 'b', 'c'];
const lastElement = arr[arr.length - 1];
console.log(lastElement); // c
Indexes are zero-based in JavaScript, that’s why we have to subtract 1 from the array’s length to get the index of the last element in the array.
Example 2: Using pop() method
You can get the last element of an array, using the pop method on the array. The pop method mutates the original array, removes and returns its last element.
const arr = ['a', 'b', 'c'];
const lastElement = arr.pop();
console.log(lastElement); // c
console.log(arr) // ['a', 'b']
Example 3: Using slice() method
To get the last element of an array you can use the slice method to pass -1 as an argument to the Array.slice method. Its returns a new array containing the last element from the original array.
let arr = [2, 4, 6, 8, 10, 12, 14, 16];
let lastElement = arryslice(-1);
console.log(lastElement); // 16
Example 4: Using Array.at() Method
Using Array.at() method to get the last element of an array in JavaScript. You just need to pass a negative index, the at() method returns an element by counting back from the end of the array.
const arr = ['a', 'b', 'c'];
const last = arr.at(-1);
console.log(last); // "c"
I hope these examples help you to get last element from an array in Javascript;