How to get the last element of Array?
Array plays a crucial role in any programming language. If we know the size of the array we can easily get its last element.
Note: The indexing of values starts from zero. Therefore, the last index of the array will be an array.length-1
let array= ['w','x','y','z']; var lastIndex = array.length-1; console.log(array[lastIndex]); // z
Using at() method
To get the last element of an array using at() method you need to use the dot operator with the function by passing a negative one(-1) as the argument.
The at(index) method takes an integer as an argument.
let array= ['w','x','y','z']; console.log(array.at(-1)); // z
Note: The at() method won’t work in the old version, use node 16.6 or greater if running in cmd or terminal.
You can use the splice() method to get the last 2 elements of the array.
const array = [1,2,3,4,5,6,7,8,9,10]; console.log(array.splice(array.length-2,array.length)); // [9,10]
const array = [1,2,3,4,5,6,7,8,9,10]; console.log(array.splice(array.length-3,array.length)); // [8,9,10]
Likewise, by using the splice method technique, you can also get the last 10 elements of an array.
const array = [1,2,3,4,5,6,7,8,9,10]; let first=array; let last=array[array.length-1]; console.log([first,last]); //[1,10]
As you can see it is super simple because we all know that the first element of the array is at its zero index and the last value at the array.length-1 index.
Feel to check exponents in java.