Check if a variable is an array in JavaScript

This tutorial will show you how you can check if a variable is an array or not in JavaScript. For this purpose, we will use Array.isArray method and instanceof operator.

Using Array.isArray method

The Array.isArray() is a static method that returns the boolean value true if the passed parameter is an array otherwise it will return false.

Here is the JavaScript program to check if a variable is an array.

const myArray = ["Aric", "Rayan", "Olson"]

const myObject = { Name: 'Sam', Age: 21};

console.log(Array.isArray(myArray));
console.log(Array.isArray(myObject));

In the above program, I have used Array.isArray() method to check whether the variables myArray and myObject are arrays or not.

The first console.log() statement will print true because myArray is an instance of the Array constructor.

And the second console.log() statement will print false because myObject is an instance of the Object constructor, not an array constructor.

Output:

true
false

 

Using instanceof operator

Here is the JavaScript program to check if a variable is an array using instanceof operator.

const myArray = ["Aric", "Rayan", "Olson"]

const myObject = { Name: 'Sam', Age: 21};

console.log(myArray instanceof Array);
console.log(myObject instanceof Array);

In the above program, I have used instanceof operator to check whether myArray and myObject are instances of the Array constructor.

Output:

true
false

 

Leave a Reply

Your email address will not be published. Required fields are marked *