How to recognize array & object in js where typeof doesn’t come in handy?
var arr = [], ob = {};
As everything in js are objects,
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