Get the First and Last Elements of an Array in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20211 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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee