Check If An Array Index Exists In JavaScript

To check if an array index exists in JavaScript, use any of the following methods –

  1. Use the arr[index] syntax to check if an index exists.
  2. Use the optional chaining operator (?.) introduced in ES 2020.
  3. Use the length property of the array. If the length of the array if greater than the index, then the index exists.

Let’s discuss each of these methods in detail.

check if an array index exists in javascript

arr[index] To Check If An Array Index Exists In JavaScript

JavaScript arrays are zero-indexed, which means the first element of an array is at index 0, the second element is at index 1, and so on.

You can use the arr[] syntax to check if a given index exists in an array or not. If the index exists, then it returns the value present at that index, otherwise it returns undefined.

For example,

let arr = [‘a’, ‘b’, ‘c’];

console.log(arr[‘0’]); // a

console.log(arr[‘3’]); // undefined

In the above example, we have declared an array with three elements – ‘a’, ‘b’, and ‘c’. We are accessing these elements using their respective indexes. Note that index 3 doesn’t exist in the array, hence it returns undefined.

Use The Optional Chaining Operator(?.) Introduced In ES 2020

The optional chaining operator (?.) introduced in ES 2020 lets you access the properties of an object even if they don’t exist. It is represented by a question mark followed by a dot (?).

For example,

let arr = [1, 2];

console.log(arr?.[0]); // 1

console.log(arr?.[3]); // undefined

In the above example, we have declared an array with two elements – 1 and 2. We are accessing these elements using their respective indexes. Note that index 3 doesn’t exist in the array, hence it returns undefined.

Use The length Property Of The Array

In JavaScript, the length property of an array returns the number of elements present in the array.

You can use the length property to check if a given index exists in an array or not. If the length of the array is greater than the index, then it means that the index exists.

For example,

let arr = [‘a’, ‘b’, ‘c’];

if(arr.length>2) {

   console.log(arr[‘2’]); // c

} else {

   console.log("Index doesn’t exist");

}

In the above example, we have declared an array with three elements – ‘a’, ‘b’, and ‘c’. We are checking if the length of the array is greater than 2. If it is, then we print the element at index 2. Otherwise, we print “Index doesn’t exist”.

Thus, you can use any of the above methods to check if an array index exists in JavaScript.

Leave a Reply