Easiest way to check if a variable is an array in Javascript

There are lots of way to check whether the var is array or not but the easiest way is using instanceof Array

Example 1 :

var myName=["Vignesh","A","Sathiyanantham"];
if (myName instanceof Array) {
alert(myName is Array!');
} else {
alert('myName Not an array');
}

This will return you myName is Array!

Example 2:

var myName="Vignesh A Sathiyanantham";
if (myName instanceof Array) {
alert(myName is Array!');
} else {
alert('myName Not an array');
}

This will return you myName Not an Array!

You can write a function to make it reusable

function ismyvararray(myVar) { 
 return (myVar instanceof Array);
}

This will return you the bool 1 if it is array

Default image
Vignesh A Sathiyanantham
AWS Certified developer with 8 years of extensive experience working for Cloud and Datacenter solutions and leading a small team in a lean startup based on Bangalore, India
Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.