How to check if a variable is an array in JavaScript?


In javascript we can check whether a variable is array or not by using three methods.

1) isArray() method

The Array.isArray() method checks whether the passed variable is array or not. If the variable is an array it displays true else displays false.

Syntax

Array.isArray(variableName)

Example

Live Demo

<html>
<body>
<script type="text/javascript">
   arr = [1,2,3,4,5];
   str = "i love my india";
   document.write( Array.isArray(arr));
   document.write("</br>");
   document.write( Array.isArray(str));
</script>
</body>
</html>

Output

true
false


2) instanceof operator

The instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In the following example the instanceof operator checks whether there exists an array prototype.

Syntax

variable instanceof Array

Example

Live Demo

<html>
<body>
<script type="text/javascript">
   arr = [1,2,3,4,5];
   str = "i love my india";
   document.write(str instanceof Array);
   document.write("</br>");
   document.write(arr instanceof Array);
</script>
</body>
</html>

Output

false
true


3) Checking the constructor property of the variable

It displays true when the variable is same as what we specified. Here we specified that the variable should be array. So when the variable is array this method displays true else displays false.

Syntax

variable.constructor === Array

Example

Live Demo

<html>
<body>
<script type="text/javascript">
   arr = [1,2,3,4,5];
   str = "i love my india";
   document.write(str.constructor === Array);
   document.write("</br>");
   document.write(arr.constructor === Array);
</script>
</body>
</html>

Output

false
true



Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements