Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
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 }
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.
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.
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.
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
.
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
.