How to check if an array index exists or not in JavaScript

Javascript check if array index exists or not example; In this tutorial you will learn how to check if array index exists or not in Javascript;

Example 1:

To check if an array index exists, we can check array at the specific index is equal to undefined then that index is not exits in array;

const arr = ['a', 'b'];

if (arr[3] === undefined) {
  // index 3 not exists in the array
}

Example 2:

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 not exists in the array
}

Example 3:

We can check the index using typeof is undefined then surely the index is not exits in that array;

const arr = ['a', 'b'];

if(typeof arr[index] === 'undefined') {
    // does not exist
} else {
    // exists
}

I hope these examples help you;