Every once in a while, I see someone talking about how to check if a thing is an array. I’ve been through a few stages of how to write an array detection utility myself.
Stage 1; “instanceof is the best!”
I’ll just check if object instanceof Array! Woohoo!
And then I came across this: http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
Huh, arrays from other frames are not instances of the Array constructor in this frame. I guess that makes sense, since it isn’t an instance of this frames Array.
Stage 2; “instanceof is the worst!”
Righto, guess I’ll use the solution provided.
The suggested solution relies on checking a string that gets spit out from Object.prototype.toString.call().
That’s great, except for this:
// -> [object Array]
Cool so now your array detection function will detect Array.prototype as an array, which it isn’t.
Shudup spec, Array.prototype isn’t an array, that would be fucking stupid. Anyway Array.prototype.instanceof Array returns false, as you would expect, because it literally isn’t an instance of Array. If you make your own constructor, you wouldn’t expect it’s prototype to be an instance of it, would you?
Really, if you’re checking that something is a thing based on some random string you pulled from a function on a different constructor… you’ve gotta expect problems.
Stage 3; “Array-detecting libraries are stupid”.
There is a huge amount of noise on the internet around this topic, and it is all noise. You will never make a perfect one-size-fits-all .isArray, Even Array.isArray() won’t work for array-like objects that people intend to be used in place of arrays. In the end, to quote greenday…
It doesn’t even matter.
- instanceof Array is NOT harmful.
- array detection libraries are stupid, think about what you actually need to check, and check for that.