JavaScript

How to Check if an Array Index Exists in JavaScript

While working with arrays, developers may need to check the index of an array whether exists or not before storing the value or performing any other activity. To do so, it is required to check the specified array index with undefined; if it gets matched with the specified index, it means the index exists in the array while being equal to undefined means the index does not exist.

This tutorial will discuss the method to check if the specified index of an array exists or not using JavaScript.

How to Check/Verify if an Array Index Exists in JavaScript?

To check if an array index exists, we will go see the provided examples.

Example 1: Check an Array Index that does not Exist Using an undefined Keyword

Create an array of numbers:

var array = [4, 6, 8, 12];

Check if the index “5” exists in the array. If it exists in the array, the value of the specified index will be returned; if not, then its outputs “undefined”:

if (array[5] !== undefined) {

  console.log(array[5]);

}

As the output shows “undefined” means the specified array index does not exist in the array:

Example 2: Check an Array Index Exists Using an undefined Keyword

Now, we will check for the index “2” in the same code; it will return the value at that index because the length of the array is “3”:

if (array[2] !== undefined) {

  console.log(array[2]);

}

The output displays value at the specified index as it exists:

Example 3: Check an Array Index Using Length Property

Another way is to check the array’s length with the help of the “length” property. Here, we access the 5th index of the array while the actual length of the array is “3”. If the length of the array is greater than “4”, then there should be an index “5” present having some value; otherwise, print the else statement:

if (array.length > 4) {

  console.log(array[5]);

}

else{

  console.log("The index 5 does not exist in array because the length of array is less than 5");

}

Output

We have compiled the different ways to determine whether the array index exists in JavaScript.

Conclusion

To determine if an array index is present in JavaScript, fetch the array at the index and verify if the returned result is not equal to “undefined”. If the result is equal to undefined, it means the array index does not exist and vice versa. Another way to perform the same operation is to use the “length” property. In this tutorial, we discussed the ways to check whether an array index exists in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.