How to recognize array & object in js where typeof doesn’t come in handy?
var arr = [], ob = {};
As everything in js are objects,
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
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
Among numerous simple/sophisticated comparisons, one difference is:
var arr = []; # arr.length => 0
var obj = {}; # obj.length => undefined
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