JS Tip of the Day: Is it an Array?

Is it an Array?
Level: Beginner

Sometimes you need an array. And if you ever need to know if some arbitrary value is an array, you should know how to accurately test for that.

We’ve seen how typeof can be used to look at value types, but it is largely only useful for primitives. When used on arrays, arrays being objects, typeof will return "object". There’s also an instanceof operator but this too has its limitations, looking only at inheritance chains and not recognizing types from other global spaces, for example from other frames or windows in browsers.

Thankfully, JavaScript has us covered here with a special function that will automatically tell us if any value is an array or not: Array.isArray(). Simply give it a value and it will tell you if it’s an array or not an array by returning true or false.

console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false

let fakeArray = Object.create(Array.prototype);
console.log(fakeArray instanceof Array); // true
console.log(Array.isArray(fakeArray)); // false

More info:

How does Array.isArray know when an array is an array?

1 Like

The answer is both simple and complicated. Simply, Array.isArray knows something is an array because it knows what an array is. As obvious as that sounds, it’s also basically how it works under the hood.

More specifically, isArray looks at the value its given and determines if that value is an array exotic object. A future tip was planned to cover exotic objects, but maybe that will get moved up and we can look at those in more detail a bit sooner [Edit: added - Exotic Objects]. Basically, some object types have special characteristics that make them special - something giving them a little more magic than what’s possible with normal objects. Arrays, for example, have a magical length property which automatically updates when you add or remove an indexed property. If you assign a value to [0] in an empty array object, its length magically becomes 1. This magic is not something you’d find in ordinary objects which makes arrays exotic. Runtimes are able to keep track and recognize exotic objects and isArray uses that to know if a certain value is, in fact, an array.

1 Like

Thanks! I look forward to your tip on exotic objects.

After reading this i decided to check my projects for game.isShit and sure enough it returns true, odd to find this since i wrote the games myself, but i cant argue with the compiler

1 Like

Have you tried setting it to false? You might be on to game of the year.

1 Like

It wont let me I’ve been trying to figure it out for 10 years

1 Like