How to Check If a Variable is an Array in JavaScript

Here are three ways to check if a variable is an array in JavaScript:

  1. Using Array.isArray()
  2. Using instanceof operator
  3. By checking the constructor type

Method 1: Using Array.isArray()

The isArray() method returns true if an object is an Array; otherwise, it returns false.

console.log(Array.isArray([11, 21, 19]))

console.log(Array.isArray({ data: 1121 }))

console.log(Array.isArray('dataset'))

console.log(Array.isArray(undefined))

Output

true
false
false
false

Method 2: Using JavaScript instanceof operator

An instanceof operator is “used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object.”

let arr = [11, 19, 21];

if (arr instanceof Array) {
  console.log('arr is an array!');
} else {
  console.log('arr is not an array.');
}

Output

arr is an array!

An important caveat is that the instanceof operator doesn’t always work across multiple frames or windows in web browsers. This is because each frame or window has its execution environment and its global object.

If you pass an array from one frame to another, it might not be recognized as an instance of an Array in the receiving frame.

Method 3: By Checking the constructor property of the variable

Another approach to check if a variable is an array in JavaScript is by using the constructor property. Every object in JavaScript has a constructor property that references the constructor function used to create the object. For arrays, this constructor is Array.

let arr = [11, 19, 21];

if (arr.constructor === Array) {
  console.log('arr is an array!');
} else {
  console.log('arr is not an array.');
}

Output

arr is an array!

If cross-frame compatibility is a concern, it’s still recommended to use Array.isArray().

Conclusion

For more robust array checking, especially when dealing with multiple frames, you can use the Array.isArray() method.

Related posts

How to Check If a Variable is a String

How to Check If Variable Exists