Get the first and last item in an array using JavaScript?


Javascript arrays are 0-indexed. This means that the first element is at the 0th position. The last element is at the length-of-array - 1th position. So we can access these elements using −

Example

arr[0] // First element
arr[arr.length - 1] // last element
For example,
let arr = [1, 'test', {}, 'hello']
console.log(arr[0])
console.log(arr[arr.length - 1])

Output

1
hello

Updated on: 16-Sep-2019

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements