Borislav Hadzhiev
Tue Oct 05 2021·2 min read
Photo by Michael Humphries
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.
const arr = ['a', 'b']; if (arr[3] !== undefined) { // 👉️ index 3 exists in the array }
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.
const arr = ['a', 'b']; if (arr.length > 5) { // 👉️ index 5 exists in the array }
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.
// 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
.
?.
is not supported in Internet Explorer versions 6-11, if you have to support the browser, use one of the other approaches.