JavaScript Enthusiast | Software Developer | Open Source Contributor | Technical Speaker

How to check if a variable is an array in JavaScript

Oct 16, 2022#JavaScript4 min read

In this post, we're going to understand how we can determine if a specified variable is an array.

Using Array.isArray method:

JavaScript's Array object comes bundled with the isArray method which can be useful in determining if a variable is an array. If the variable is an array, the isArray method will return true else it'll return false.

const nums = [1, 2, 3, 4, 5];
const user = { name: 'John Doe', city: 'Calgary' };
const price = 100;
const message = "hello world!";
const emptyValue = null;

Array.isArray(nums); // true
Array.isArray(user); // false
Array.isArray(price); // false
Array.isArray(message); // false
Array.isArray(emptyValue); // false

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 nums = [1, 2, 3, 4, 5];
const user = { name: 'John Doe', city: 'Calgary' };
const price = 100;
const message = "hello world!";
const emptyValue = null;

nums instanceOf Array; // true
user instanceOf Array; // false
price instanceOf Array; // false
message instanceOf Array; // false
emptyValue instanceOf Array; // 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 nums = [1, 2, 3, 4, 5];
const user = { name: 'John Doe', city: 'Calgary' };
const price = 100;
const message = "hello world!";

Object.getPrototypeOf(nums) === Array.prototype; // true
Object.getPrototypeOf(user) === Array.prototype; // false
Object.getPrototypeOf(price) === Array.prototype; // false
Object.getPrototypeOf(message) === Array.prototype; // false

And that's it. Hope you enjoyed this short post. In case you've any query or question feel free to drop a comment.