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?
Arrays 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
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