Search⌘ K
AI Features

Solution Review: Array or Not?

Explore how to identify whether a variable is an array in JavaScript by using Object.prototype.toString with call to check the internal [[Class]] of the object. Understand why this method works reliably and how type detection relates to prototypes and inheritance.

We'll cover the following...

Solution

Javascript (babel-node)
function check(obj) {
if (Object.prototype.toString.call(obj) === "[object Array]") {
return true;
} else {
return false;
}
}
console.log(check(123));
console.log(check("cat"));
console.log(check([1, 2, 3, 4]));

Explanation

To check whether the passed in object is an array or ...