Understanding the typeof operator in Javascript
This is slightly odd, idiosyncratic Javascript behaviour. It's inherited from the earliest days of Javascript and probably would not be written in such a way today.
Nonetheless, we are where we are with Javascript, so we have to deal with it!
The thing is that values in Javascript are either objects or they are primitives. This is a design decision. They cannot be anything else. The types of primitives are:
- strings
- numbers
- booleans
- symbols (from ES2015)
- the special value
undefined
- the special value
null
(for whichtypeof
also returnsobject
)
Anything and everything else is an object. This is by design. Arrays are objects, so typeof
returns object
, as does every other object that is not callable (i.e. a function). See the spec for typeof
.
The better question is to ask why you want to test if something is an array. You probably don't need to, especially as array-like objects such as NodeLists are not arrays but are like them in many ways.
The best solution in most cases is to call Array.from
on the value supplied: then you know that it is an array.