How to Check if Something is an Array in JavaScript?

How to Check if Something is an Array in JavaScript?

Ferenc Almasi β€’ 2020 August 17 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

When checking if something is an array in JavaScript, you can't rely on the typeof operator because that just returns object.

Instead, here are four tips you can use to truly be sure you are dealing with an array:

Copied to clipboard!
// Truly check if something is an array in the following ways
const stats = [123, 654, 879];

stats.constructor === Array; // returns true
isArray.js

All objects in JavaScript have a constructor property. Except the ones created with Object.create(null). It returns a reference to the Object constructor function that created the instance object. If this equals to Array, you can be sure your variable is an array as well.

Copied to clipboard!
stats instanceof Array; // returns true
isArray.js

You can also use the instanceof operator to check whether Array appears anywhere in the prototype chain. If it is, then it means your variable is an array.

Copied to clipboard!
Object.prototype.toString.call(stats) === '[object Array]'; // returns true
isArray.js

Calling Object.prototype.toString, return the type of the object in a stringified version. Since you want to check the type of your variable, you need to call this method with the proper object. This is why you also need to append .call(stats). If this returns "[object Array]", you can be sure, you are dealing with an array.

Copied to clipboard!
Array.isArray(stats) // returns true
isArray.js

Lastly, you can also use the built-in isArray function to check whether your variable is an array or not. This is the simplest and most elegant solution. Whenever you can, always go with this.

How to Check if Something is an Array in JavaScript?
If you would like to see more Webtips, follow @flowforfrank

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.