Javascript: Check if a variable is an Array

This article shows how you can check if a Javascript variable is of an Array type.

There are different ways to check if a variable is an Array in Javascript.

1) First way


// define an array
var myArray = [11, 'John'];

console.log(Object.prototype.toString.call(myArray)); // [object Array]

// check if the variable is an array
if (Object.prototype.toString.call(myArray) === '[object Array]') {
    console.log('The variable is an array.');
} else {
    console.log('The variable is NOT an array.');
}

// for object, you will get [object Object]
var myObject = {id: 11, name: 'John'};
console.log(Object.prototype.toString.call(myObject)); // [object Object]

2) Second way

Array.isArray() method was introduced in ECMAscript 5 (ES5).


var myArray = [id: 11, name: John];
var isArray = Array.isArray(myArray);
console.log(isArray); // true

3) Third way

Using instanceof operator


// using object instanceof and constructor operator
function isArray(arr) {
  return arr instanceof Object && arr.constructor === Array;
}

console.log(isArray(myObject)); // false
console.log(isArray(myArray)); // true

Using typeof operator


// using object typeof and constructor operator
function isArray(arr) {
  return typeof arr === 'object' && arr.constructor === Array;
}

console.log(isArray(myObject)); // false
console.log(isArray(myArray)); // true

Here’s the difference between typeof and instanceof:

instanceof operator tests the presence of constructor.prototype in object’s prototype chain.

typeof operator returns a string indicating the type of the operand. The operand can be an object or primitive value like string, number, null, undefined, etc.


const a = "Primitive String";
const b = new String("String Object");

console.log(typeof a); // output: string
console.log(typeof b); // output: object

console.log(a instanceof String); // output: false
console.log(b instanceof String); // output: true

Hope this helps. Thanks.