How to check if an Array Index exists in JavaScript

avatar

Borislav Hadzhiev

2 min

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 }

JavaScript indexes are zero-based, so the first index in an array is 0 and the last index is equal to array.length - 1.

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.

Check if an Array Index exists using the array's length #

Use the array's 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 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.

JavaScript indexes are zero-based, 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.

Check if an Array Index exists using 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 access the array elements at indices 1 and 5.

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

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

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.

Copyright ยฉ 2023 Borislav Hadzhiev