x
is an array.
I do console.log(x)
I got
[ 'value' ]
but when I check the x with type of like console.log(typeof x)
it says it's an Object. Why?
x
is an array.
I do console.log(x)
I got
[ 'value' ]
but when I check the x with type of like console.log(typeof x)
it says it's an Object. Why?
7 Answers
Reset to default 6Arrays are objects in JS.
If you need to test a variable for array:
if (x.constructor === Array)
console.log('its an array');
According to MDN, there is no array type in javascript when using typeof There is only object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
if your purpose is to check, the "is it Array or not" ? you better use
Array.isArray()
The Array.isArray() method returns true if an object is an array, false if it is not. LINK
so you can try
if(typeof x === 'object' && Array.isArray(x)) {
//Its an array
}
UPDATE:
Array is an object, so typeof x
reports its an object. but then why on earth typeof function
reports it correctly!!! ? Good question . take good care while using typeof
Array is an Object type, so it's fine !
X is an Array defined in global scope. So, when you do console.log(x), you are able to see
['value']
Also, refer here for details about JavaScript data types which says,
Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property
Hence the type return as Object is correct and as expected.
there isn't "Array" type in javascript
typeof ['1'];//object
typeof {};//object
typeof null;//object
other often used value type:
number,string,undefined,boolean,function
The typeof operator threw me off a couple times before I discovered that arrays, null, and objects will all return as 'object'. I threw together this quick and dirty function that I now use in place of typeof - which still returns a string indicating the variable type:
TestType = (variable) => {
if(Array.isArray(variable)){
return 'array'
}
else if(variable === null){ //make sure to use the triple equals sign (===) as a double equals sign (==) will also return null if the variable is undefined
return 'null'
}else{
return typeof variable
}
}
array
is of typeobject
– Rayon Commented Jan 28, 2016 at 7:30typeof
– Shubh Commented Jan 28, 2016 at 7:31