How to Check if Something is an Array?
There are several options to check if something is an array in JavaScript. Here are four known ways to choose from:
// Check the constructor
variable.constructor === Array
The constructor
method is a special method of objects, that is used for initialization. You can check whether this is an Array
.
// Check if the variable is an instance of Array
variable instanceof Array
You can also use the instanceof
operator to test whether your variable is originating from the global Array
object.
// Check its prototype
Object.prototype.toString.call(variable) === '[object Array]';
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.
// Use the built-in isArray method
Array.isArray(variable);
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.
Resources:
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: