How do I check if a variable is an array in JavaScript?
When it comes to identifying if variable
is an Array, use Array.isArray()
for a definitive true
or false
:
Deep Dive: Scrutinize That Variable
In JavaScript, a bounty of options is available for the scenario where you need to determine if a variable is an array, each with its own trade-offs.
1. The Standard: Array.isArray()
The go-to method for checking if a variable is an array is Array.isArray()
:
This method is the belle of the ball due to its simplicity, universal support, and accuracy.
2. Quick-and-Dirty: The Constructor Property
Want a quick check with no frills? Go ahead and use the constructor
property:
Although quick, this method might bluff and give false negatives if the constructor
property has been tampered with.
3. Popular Kid in Town: instanceof
The instanceof
operator is a common sight when identifying types:
It’s easy on the eyes and fair when it comes to performance. Beware of its issues with objects from different frames, though!
4. The Absolute Unit: Object.prototype.toString.call()
If you are the one writing chess while others are playing checkers, this method is your pal:
This method assures universal reliability. Warning: it is a bit sluggish when compared to Array.isArray()
.
5. Always Ready: Polyfills for Legacy Browsers
Stuck in a jam with outdated environments? A polyfill is your savior to leverage the modern Array.isArray()
:
6. Unsung Heroes: Array-like Objects
Watch out for array-like objects! These bad boys (such as the arguments
object) fail the Array.isArray()
check but mimic some array behaviors:
7. Library Specific Methods
Library-specific solutions like jQuery.isArray(obj)
or _.isArray(obj)
from jQuery and underscore.js, respectively, ensure compatibility with a project using those libraries.
Picking the Right Check
Choosing the right method for the right job saves you from potential headaches down the road. Here are some situations where one method shines over the others:
Array.isArray()
: Ideal when accuracy and readability are prioritized, and there's no requirement to support antiquated environments.Object.prototype.toString.call()
: Perfect for multi-context environments (like different frames or windows) or when built-in prototypes may have been modified.variable.constructor === Array
: When speed is the goal, but be aware of its propensity for false negatives.variable instanceof Array
: Use this only if objects from different global execution contexts (like iframes) are not on the radar.- Custom
isArray
function: Creating a dedicated function for checking can make your code cleaner when checking arrays repeatedly across your application:
Was this article helpful?