foo; // ReferenceError: foo is not defined
typeof(foo); // undefined
How does typeof
circumvent the ReferenceError
when supplied an undeclared variable identifier? Is this just JavaScript interpreter "magic" or can it be explained in terms of user-land concepts?
No, this cannot be explained in user-land concepts - it's "magic" if you want.
EcmaScript uses the Reference specification type to explain cases like this. These references are used to describe the semantics of assignments, method calls,
eval
and many more. Typically, the GetValue algorithm is called on them to dereference them (e.g. in the evaluation of your expression statement), and this does throw theReferenceError
when the reference is not resolvable.The
typeof
operator in contrast does not just do GetValue, but has a special case to handle these undeclared-variable references: