SoFunction
Updated on 2025-03-01

Determine whether a variable is an array or an object in Javascript (array or object)

How to determine whether a JavaScript variable is an array or an object?
Answer:
1. If you just use typeof to check the variable, whether it is an array or an object, it will return ‘objec’.
A viable answer to this question is to check if the variable is an object and to check if the variable has a numeric length (the length may also be 0 when an empty array).
However, the parameter object (all parameters passed to the formulating function) may also be applicable to the above methods. Technically, the parameter object is not an array.
In addition, when an object has properties, this method does not work.
Copy the codeThe code is as follows:

// Real array The array
var my_array = [];
// Imposter! Imposter!
var my_object = {};
my_object.length = 0;
// Potentially faulty Potential error
function is_this_an_array(param) {
if (typeof param === 'object' && !isNaN()) {
('Congrats, you have an array!');
}
else {
('Bummer, not an array');
}
}
// Works Success
is_this_an_array(my_array);
// Works, but is incorrect
is_this_an_array(my_object);

2. Another answer to this question is to use a more hidden method, calling the toString( ) method to try to convert the variable into a string representing its type.
This method is feasible for real array; returning [object Arguments] when the parameter object is converted to string will fail; in addition,
The conversion will also fail for object classes containing numeric length attributes.
Copy the codeThe code is as follows:

// Real array Real array
var my_array = [];
// Imposter! Imposter!
var my_object = {};
my_object.length = 0;
// Rock solid is as solid as a rock (test function)
function is_this_an_array(param) {
if ((param) === '[object Array]') {
('Congrats, you have an array!');
}
else {
('Bummer, not an array');
}
}
// Works succeeded
is_this_an_array(my_array);
// Not an array, yay! Not an array!
is_this_an_array(my_object);

3. In addition, instanceof is a perfect and suitable operation in a multi-frame DOM environment that may be unreliable.
Extended reading: "Instanceof Considered Harmful..."
/instanceof-considered-harmful-or-how-to-write-a-robust-isarray
Copy the codeThe code is as follows:

var my_array = [];
if (my_array instanceof Array) {
('Congrats, you have an array!');
}

4. For Javascript 1.8.5 (ECMAScript 5), the variable name.isArray( ) can achieve this goal.
/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
Copy the codeThe code is as follows:

var my_array = [];
if ((my_array)) {
('Congrats, you have an array!');
}