Reputation: 9310
How to recognize array & object in js where typeof doesn’t come in handy?
var arr = [], ob = {};
As everything in js are objects,
if(typeof arr == typeof ob) => returns true
I want a operator or ... that will tell me that the variable is an array. I can then use only the arrayfunctions to objects which are array. How is that possible?
Upvotes: 26
Views: 21446
Reputation: 1
You can know only true objects this way:
if (typeof x === "object" && !(x instanceof Object && x instanceof Array)) console.log(x);
where x
is the variable. This will produce only objects without arrays.
Upvotes: 0
Reputation: 1418
There are multiple ways of differentiating between array and object, some on them are already mentioned above i would like to just add on above answers.
First Approach Differentiation using length, length property exist on Array but doesn't exist on Object
var arr = [1,2,3]; arr.length => 3
var obj = {name: 'name'}; obj.length => undefined
Note: This approach fails when someone declares object like below, we can use this approach only when we are sure we will not get any object having length property
var rectangle = {length: 50, width: 50}; rectangle.length => 50
Second Approach Using instanceof Array
var arr = [1,2,3]; arr instanceof Array => true
var obj = {name: 'name'}; ojb instanceof Array => false
Third Approach Using Array.isArray, this is most preferable approach and is supported by most of browser now
Note: Array.isArray is preferred over instanceof because it works through iframes.
Array.isArray(arr) => true
true
Array.isArray(obj) => false
If you want to support i.e 8 browser the use Object.prototype.toString We can write polyfill for i.e 8
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
Object.prototype.toString.call(arr); =>"[object Array]"
Object.prototype.toString.call(obj); =>"[object Object]"
Reference: isArray
Upvotes: 6
Reputation: 146
Among numerous simple/sophisticated comparisons, one difference is:
var arr = []; # arr.length => 0
var obj = {}; # obj.length => undefined
Upvotes: 7
Reputation: 636
You could use Array.isArray() method to check if a variable is array or otherwise.
var myArray = [1,2,3,4,5];
console.log(Array.isArray(myArray));
true
Upvotes: 23
Reputation: 9310
var arr = [], ob = {};
As everything in js are objects, even **Array is an Object but an instance of class Array
if(typeof arr == typeof ob) => returns true as Both are **Objects
So, how will you to identify objects.
This is where instanceof operator comes in handy, to identify whether its an array you can put a additional check cde:
if(arr instanceof Object && arr instanceof Array) => returns true
if(ob instanceof Object && ob instanceof Array) => returns false
Upvotes: 42