typeof []
The typeof operator in JavaScript returns the type of a value as a string.
But it has one non-obvious behavior - with arrays.
Example:
javascript
console.log(typeof []); // "object"Yes, an array returns "object" - not "array".
Why is that?
Because in JavaScript an array is a special case of an object. Internally it is implemented as an object, where:
- the keys are numeric indexes (
"0","1","2"), - and the
lengthproperty tracks the number of elements.
Example:
javascript
const arr = ["a", "b"];
console.log(Object.keys(arr)); // ["0", "1"]How to correctly check that it is actually an array
Use:
javascript
Array.isArray([]);or
javascript
[] instanceof Array;Both options return:
javascript
trueIn short:
| Check | Returns | Comment |
|---|---|---|
typeof [] | "object" | because an array is an object |
Array.isArray([]) | true | the correct way |
[] instanceof Array | true | also correct, but depends on the environment |
Summary:
typeof []->"object"because arrays are special objects, optimized for storing ordered data.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.