Get last value of array in JavaScript

Sometime we need to get last element of array. Even when we do not know size of array. There are several way to achieve it. Lets explore few ways.

1. Using index and length

Syntax: arr[arr.length-1]

arr = [1,2,3,46]
1. Find length
let len = arr.length;
2. Find element
elem = arr[len - 1];

2. Using splice

Syntax: [..].splice(-1).pop()

arr = [1,2,3,46]
1. Find element
elem = arr.splice(-1).pop();

3. Using slice

Syntax: [..].slice(-1).pop()

arr = [1,2,3,46]
1. Find element
elem = arr.slice(-1).pop();

Leave a Reply