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:
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”:
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”:
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:
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.