Get the First and Last Elements of an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 23, 2022

banner

Photo from Unsplash

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
JavaScript indexes are zero-based. The first element in an array has an index of 0 and the last element in an 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.

index.js
const arr = ['a', 'b', 'c', 'd']; const last = arr[arr.length - 1]; console.log(last); // 👉️ d

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

index.js
const arr = ['a', 'b', 'c', 'd']; const last = arr[arr.length - 2]; console.log(last); // 👉️ c

Trying to access an array element at an index that doesn't exist doesn't throw an error, 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

Alternatively, you can use the Array.at() method.

Get the First and Last Elements of an Array using Array.at() #

Use the Array.at() method to get the first and last elements of an array. For example, arr.at(0) returns the first element and arr.at(-1) returns the last array element.

index.js
const arr = ['a', 'b', 'c', 'd']; const first = arr.at(0); console.log(first); // 👉️ a const last = arr.at(-1); console.log(last); // 👉️ d

We used the Array.at method to get the first and last elements in an array.

The Array.at() method takes an integer that represents the index of the value to be returned.

The method supports negative integers to count backwards. For example, -1 returns the last element in the array and -2 returns the second last element.

The Array.at() method returns the element at the specified index or -1 if the index is out of range.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.