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?
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays.
An array is an object. And like any object in JavaScript, the array instance has a constructor function — Array .
Javascript is case sensitive "object" is essentially a variable that can hold anything. "Object" is an actual javascript type.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With