How to check if an Array Index exists in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20212 min read

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.

In the code snippet, we access the array at index 3 and check if the result is not equal to undefined.

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

An alternative way to check if an array index exists is to check for the array's length.

index.js
const arr = ['a', 'b']; if (arr.length > 5) { // ๐Ÿ‘‰๏ธ index 5 exists in the array }
In the example, 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 on the array.

Since indexes are 0 based in JavaScript, the last index is equal to array.length - 1.

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

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

To check if an array index exists, use the optional chaining operator to access the array element at that index, e.g. arr?.[3]. If the return value is anything other than undefined, then the array index exists.

index.js
// Not Supported in IE 6-11 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

In the code snippet we use 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 variable firstIndex.

The array element at index 5 doesn't exists so it evaluates to undefined.

Note that the optional chaining operator ?. is not supported in Internet Explorer versions 6-11, if you have to support the browser, use one of the other approaches.

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