How to check if an Array Index exists in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if an Array Index exists in JavaScript #

To check if an array index exists, access the array at the specific index and check if the result is not equal to undefined. If the result is not equal to undefined the array index exists.

index.js
const arr = ['a', 'b']; if (arr[3] !== undefined) { // 👉️ index 3 exists in the array }
Indexes are 0 based in JavaScript.

We access the array at index 3 and check if the result is not equal to undefined.

Since the array only has 2 elements, the last index in the array is 1. Therefore, the condition is never satisfied and the if block doesn't run.

Alternatively, you can check for the array's length.

Use the length property to check if an array index exists, e.g. if (arr.length > 5) {}. If the array has a length greater than N, then index N is guaranteed to exists in the array.

index.js
const arr = ['a', 'b']; if (arr.length > 5) { // 👉️ index 5 exists in the array }
We check if the length of the array is greater than 5. If the array has a length greater than 5, then index 5 is guaranteed to exist in the array.

Indexes are zero-based in JavaScript, so the last index in the array is equal to array.length - 1.

If an array has a length of 10, its last index is 10 - 1 = 9.

A newer way to check if an array index exists is to use optional chaining.

Use the optional chaining operator to check if an array index exists, e.g. const firstIndex = arr?.[1]. The optional chaining operator will return the array element if the index exists, otherwise it returns undefined.

index.js
const arr = ['a', 'b']; const firstIndex = arr?.[1]; console.log(firstIndex); // 👉️ b if (firstIndex !== undefined) { // 👉️ index 1 exists in the array } const fifthIndex = arr?.[5]; console.log(fifthIndex); // 👉️ undefined

We used the optional chaining operator (?.) to to access the array elements at index 1 and 5.

The array element at index 1 exists, therefore its value is assigned to the firstIndex variable.

The array element at index 5 doesn't exist, so the optional chaining operator short-circuits returning undefined.

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.