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

JavascriptFront End TechnologyObject Oriented Programming

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
raja
Published on 16-Sep-2019 07:32:55
Advertisements