How to Check if Something is an Array?

How to Check if Something is an Array?

Ferenc Almasi β€’ Last updated 2020 November 01 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

There are several options to check if something is an array in JavaScript. Here are four known ways to choose from:

Copied to clipboard!
// Check the constructor
variable.constructor === Array
constructor.js

The constructor method is a special method of objects, that is used for initialization. You can check whether this is an Array.

Copied to clipboard!
// Check if the variable is an instance of Array
variable instanceof Array
instanceof.js

You can also use the instanceof operator to test whether your variable is originating from the global Array object.

Copied to clipboard!
// Check its prototype
Object.prototype.toString.call(variable) === '[object Array]';
prototype.toString.js

A more verbose way is to call the prototype of the global Object and turning the result into a string, by using your variable as the this argument. If this equals to [object Array], you can be sure you are dealing with an array.

Copied to clipboard!
// Use the built-in isArray method
Array.isArray(variable);
isArray.js

Lastly, you can use the built-in isArray method, which expects the variable to check.

So which one to go with? If you can, go withArray.isArray as that is the cleanest and most readable solution. It is also widely supported.

How to check if something is an array in JavaScript?
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.