How to check if a variable is array type in Javascript

Description

We have two ways to check if a variable is an array. The first method is to use instanceof operator.


if (value instanceof Array){ 
  //do something on the array 
}

The second one is to use Array.isArray() method.


if (Array.isArray(value)){ 
//do something on the array 
}

Example


var colors = ["A", "B", "C"]; 
//creates an array with three strings 
//  w w  w.  j  a v a2s  .co  m
if (Array.isArray(colors)){ 
   console.log("colors is an array");
} 

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions