Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof something return object instead of array

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?

like image 455
Jennifer Avatar asked Jan 28 '16 07:01

Jennifer


3 Answers

Arrays are objects in JS.

If you need to test a variable for array:

if (x.constructor === Array)
   console.log('its an array');
like image 73
Charlie Avatar answered Oct 28 '22 18:10

Charlie


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

like image 21
Sarawut Positwinyu Avatar answered Oct 28 '22 17:10

Sarawut Positwinyu


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

like image 2
Oxi Avatar answered Oct 28 '22 18:10

Oxi