JavaScript · The language round
What are the quirks of the typeof operator?
Short answer
typeof returns a string describing the operand, but typeof null is "object" and arrays and dates also return "object". typeof on an undeclared identifier returns "undefined" instead of throwing.
typeof is useful for primitive checks, but it is not a general-purpose type inspector. A few results surprise people because of history and because arrays are objects.
typeof undefined; // "undefined"
typeof null; // "object"
typeof 42; // "number"
typeof 42n; // "bigint"
typeof "text"; // "string"
typeof true; // "boolean"
typeof Symbol(); // "symbol"
typeof function () {}; // "function"
typeof []; // "object"
typeof new Date(); // "object"The two gotchas
typeof nullis"object"because of a bug in the original JavaScript implementationtypeofon an undeclared identifier returns"undefined"rather than throwing, unlike most variable access- Arrays need
Array.isArray(value) - Dates need
value instanceof DateorObject.prototype.toString.call(value)
For NaN, typeof is "number", which is correct: NaN is a numeric value. Use Number.isNaN() to detect it.
Array.isArray([]); // true
Array.isArray({ length: 0 }); // false
Object.prototype.toString.call(new Date()); // "[object Date]"typeof value === "object" to detect a plain object: null, arrays and dates all pass that check. Add value !== null, then exclude arrays and other built-ins.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is `typeof null` equal to `"object"`?
- 2How do you check whether a value is an array?
- 3What does `typeof` return for an undeclared variable?
- 4How do you detect NaN?
Say it in the interview
typeof returns a string like number, string, boolean, function, or object. The two famous quirks are that typeof null is object and typeof an undeclared variable is undefined without throwing. Arrays and dates also report object, so I use Array.isArray for arrays and instanceof Date for dates. For NaN, typeof is number, and Number.isNaN is the correct check.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.