How to Check If a Variable is an Array in JavaScript

TL;DR

To check if a variable is an array, you use the Array.isArray() method or the instanceof operator:

let colors = ['red','green','blue'];

// #1: use Array.isArray
let isArray = Array.isArray(colors);
console.log(isArray); // true;

// #2: use instanceof operator
isArray = colors instanceof Array;
console.log(isArray); // true;Code language: JavaScript (javascript)

1) Using Array.isArray(variableName) method to check if a variable is an array

The Array.isArray(variableName) returns true if the variableName is an array. Otherwise, it returns false.

The Array.isArray() method is a recommended way to check if a variable is an array because it has good browser support.

The following shows some examples of using the Array.isArray() method:

const ratings = [1, 2, 3, 4, 5];
const vote = { user: 'John Doe', rating: 5 };
const str = "It isn't an array";

console.log(Array.isArray(ratings)); // true
console.log(Array.isArray(vote)); // false
console.log(Array.isArray(str)); // falseCode language: JavaScript (javascript)

2) Using the instanceof operator to check if a variable is an array

Since all arrays are instances of the Array type, you can use the instanceof to check if a variable is an array like this:

variableName instanceof ArrayCode language: JavaScript (javascript)

The expression returns true if the variableName is an array. For example:

const ratings = [1, 2, 3, 4, 5];
const vote = { user: 'John Doe', rating: 5 };
const str = "It isn't an array";

console.log(ratings instanceof Array); // true
console.log(vote instanceof Array); // false
console.log(str instanceof Array); // false
Code language: JavaScript (javascript)

Summary

  • The Array.isArray(variableName) returns true if the variableName is is an array.
  • The variableName instanceof Array returns true if the variableName is an array.
Was this tutorial helpful ?