How to Check If an Array Index Exists in JavaScript

Here are three ways to check if an array index exists in JavaScript:

  1. Using in operator
  2. Checking against undefined
  3. Using the hasOwnProperty method

Method 1: Using in operator

The in operator returns true if the specified property/index exists and false otherwise.

let arr = [10, 20, 30];

console.log(1 in arr);
console.log(5 in arr);

Output

true
false

Method 2: Checking against undefined

You can check if an array index exists by trying to access an array that does not exist, and JavaScript will return undefined.

let arr = [10, 20, 30];

console.log(arr[1] !== undefined);
console.log(arr[5] !== undefined);

Output

true
false

However, be careful with this method because an array can have an index with a value of undefined, which would give a false negative:

let arr = [10, undefined, 30];

console.log(arr[1] !== undefined);

Output

false

Method 3: Using hasOwnProperty()

The hasOwnProperty() method is used to check if an object (and arrays are a type of object in JavaScript) has a specific property:

let arr = [10, 20, 30];

console.log(arr.hasOwnProperty(1));
console.log(arr.hasOwnProperty(5));

Output

true
false

Conclusion

The “in operator” is the most straightforward and clear way to check if an array index exists. However, the most appropriate method depends on your specific use case and requirements.