How to Check If a Variable is an Array in JavaScript

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

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

Method 1: Using Array.isArray() method

To check if a Variable is an array in JavaScript, you can use the “array.isArray()” function. The “isArray()” function returns true if an object is an Array; otherwise, it returns false.

Syntax

Array.isArray(obj)

Parameters

obj: It is an object to be tested.

Return Value

It returns a Boolean value. It returns true if the object is an array. Otherwise, it returns false.

Example

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.”

Syntax

variable instanceof Array

Return value

An instance operator returns a true boolean value if the variable is the same as what is specified and a false if it is not.

Example

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.

Syntax

variable.constructor === Array

Example

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 a Variable is a String in TypeScript

How to Check If Variable Exists

Leave a Comment