How can I check if an object is an array?
The hero of our story is Array.isArray()
— it's the quickest and most reliable method to determine if an item is an array, and it doesn't get fooled.
Going beyond Array.isArray()
There are times when Array.isArray()
isn't supported, such as in older browsers and quirky JavaScript environments. Here are your options then:
Using legacy methods
- Play detective with
Object.prototype.toString.call(variable)
, it'll give you[object type]
wheretype
can beArray
. - Deploy the simple
variable instanceof Array
, but be advised, this method gets confused when dealing with iframes. - Rely on the
constructor
property usingvariable.constructor === Array
. Watch out though, this one trips over window or frame boundaries.
Handling non-array types
- When a dish best served as an array, use
Array.from(variable)
to convert array-likes and iterables into bona fide arrays. - Encase non-array items within an array using
[].concat(variable)
or[variable]
. Comes handy when you don't want the no-arrays-allowed party crashers.
Dealing with strings
- Confirm
variable
is not stringing you along withtypeof variable === 'string'
, before morphing it into an array. - Transform single or multiple string inputs into arrays via
[].concat(variable.split(''))
or[variable.split('')]
, because variety is the spice of coding life.
Beware of caveats
- Run a
!!variable
check first to prevent type-checking errors, because nobody likes a crash, digital or otherwise.
Array imposters
Array-like objects can fool you into thinking they're real arrays. Here's how you can spot the difference:
Spotting fakes
- Array-like objects may look and walk like arrays, but they don't talk like arrays, missing array-specific methods like
pop
,push
etc. - Don't be duped by
arguments
,NodeList
, and custom objects, they may show you theirlength
property, but they don't inherit fromArray.prototype
.
In the modern age of ES6
Remember, the world has moved on to ES6 and so have arrays. With new syntax and features, arrays have become easier to deal with.
ES6 and array handling
Array.from()
not only checks but converts array-likes and iterables to arrays, doing two tasks for the price of one.- The spread syntax like
[...array1, ...array2]
helps you combine arrays, curved swords, dragon bones... wait, wrong script!
Watch out for TypedArray
s
- Watch out for the type-casting wizards called
TypedArray
s, they may seem like arrays, but they're just mimicking them.
A word on performance
Performance matters, especially when you're handling large volumes of data:
Testing your methods
- Test out different array-checking techniques on benchmarking platforms like jsben.ch to see which is the speedy gonzales.
- Remember, performance can vary across browsers and engines. Like, Firefox may feel different from Chrome, also, engines matter (V8, SpiderMonkey, you get the idea).
Code optimisation
- Paranoid about speed? Cache the
Array.isArray()
technique, especially when using within tight loops. - And definitely avoid recalculations or multiple conversions within loops. Like mama always says, don't repeat yourself (DRY).
When even Array.isArray fails?
In super rare cases, even Array.isArray
may not be available. Polyfill to the rescue!
Writing a polyfill
- Bring in an imposter to act like
Array.isArray
withObject.prototype.toString.call(variable) === '[object Array]'
. - Hide it behind
Array.isArray
if the real McCoy doesn't exist.
One last type check
- As always, before implementing a fallback, feature-detect to safeguard against potential over-optimizations.
In conclusion
Remember: Coding is like playing a musical instrument. The key is practice. Go forth and multiply...err...code! If this answer rocks your boat, do vote it up! Happy Coding!👩💻
Was this article helpful?