Get the First and Last Elements of an Array in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20212 min read

banner

Photo by Andrew Ly

Get the First and Last Elements of an Array #

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr.length - 1] returns the last element of the array.

index.js
const arr = ['a', 'b', 'c', 'd']; const first = arr[0]; console.log(first); // 👉️ a const last = arr[arr.length - 1]; console.log(last); // 👉️ d
Indexes are zero-based in JavaScript. This means that the first element in the array has an index of 0 and the last element in the array has an index of arr.length - 1.

To get the index of the last element we subtract 1 from the array's length, because the first element in the array has an index of 0.

If you had to get the second last element from an array you would have to subtract 2 from the array's length.

Note that trying to access an array element at an index that does not exist does not throw an error, instead it returns undefined.

index.js
const arr = []; const first = arr[0]; console.log(first); // 👉️ undefined const last = arr[arr.length - 1]; console.log(last); // 👉️ undefined

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.