What does typeof return for a variable that was never declared?
typeof returns the string "undefined" for an undeclared name and does not throw. Reading the same name any other way throws a ReferenceError.
Explain it simply
Imagine asking a receptionist, "Is there a guest called Meena?" If nobody by that name is on the list, a polite receptionist says "no such guest". Reading a variable normally is like demanding to speak to Meena: if she does not exist, you get an error.
typeof is the polite question. It is the one operator that is safe to use on a name that has never been declared, so it is handy for feature checks such as "is this library loaded?".
One catch: a variable in the temporal dead zone (a let or const used before its line runs) is declared, so typeof on it still throws.
Example
console.log(typeof neverDeclared); // Output: undefined
console.log(typeof 42); // Output: number
console.log(typeof "hi"); // Output: string
try {
console.log(neverDeclared);
} catch (e) {
console.log(e.name); // Output: ReferenceError
}A common real use:
if (typeof window !== "undefined") {
// safe to touch the browser here
}What to say in the interview
"typeof on an undeclared identifier returns the string 'undefined' instead of throwing, which makes it the safe way to test whether a global exists. A direct read throws ReferenceError. The exception is the temporal dead zone, where typeof on a let or const still throws."
Common mistakes
- Confusing an undeclared variable with a variable holding undefined: both give "undefined" from typeof, but only one throws when read.
- Forgetting that typeof returns a string, so compare with "undefined" in quotes.