How To Check If A Variable Is An Array In JavaScript

Checking if a variable is an array in JavaScript is one of the most common tasks you may encounter while building a Javascript-based application. There are several ways to perform this check, each with its pros and cons. In this post, we'll review three ways to determine if a variable is an array in JavaScript.

Using the Array.isArray() method

You can use the Array.isArray() method to determine whether a variable is an array. This function is a type checker provided by the JavaScript language, which means it is a reliable and efficient way to check the type of an object.

To use this method, you need to pass the variable you want to check as an argument. If the variable is an array, the function will return true. Otherwise, it will return false.

Let's understand this in detail using an example:

const myArr = [1, 2, 3];
const myObj = {name: "John"};

console.log(Array.isArray(myArr)); // Output: true
console.log(Array.isArray(myObj)); // Output: false

The first console.log will output true since myArr is an array. However, the second console.log statement will return false since myObj is an object.

Using instanceOf operator

We can use the instanceOf operator to check if a variable is an instance of the Array object. If the comparison evaluates to true, then the variable is an array otherwise, it is not.

const myArr = [1, 2, 3];
const myObj = {name: "John"};

myArr instanceOf Array; // output: true
myObj instanceOf Array; // output: false

By comparing the prototype of the variable with Array.prototype

Another way you can check if the variable is an array is by comparing the prototype of the variable with Array.prototype property. If the variable is an array, the comparison will evaluate to true.

const myArr = [1, 2, 3];
const myObj = {name: "John"};

Object.getPrototypeOf(myArr) === Array.prototype; // output: true
Object.getPrototypeOf(myObj) === Array.prototype; // output: false

And that's it. I hope you enjoyed this short post. If you've any queries or feedback, feel free to comment.