Working with JavaScript arrays is fun. But what if we want to get the last element of an array? Maybe the last 2 or the last 3 elements of an array.

An additional case can be to find the first and last element of the array. In this quick JavaScript tutorial, you will learn how to get those last elements or items from the array.

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.

In JavaScript to find the length of any given array, we use array.length

Note: The indexing of values starts from zero. Therefore, the last index of the array will be an array.length-1

Here is a JavaScript code example-


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.

Javascript code example get the last element of an array using at() method-


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.

Get the last 2 elements of array javascript

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]

Also, we can get the last 3 elements of array javascript.


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.

Get the first and last element of the array in JavaScript

What if you want to get the first and last item of a given array.  Here is the JavaScript code example-


const array = [1,2,3,4,5,6,7,8,9,10];

let first=array[0];
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.

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed.