3
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?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331

1 Answers1

7

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 the ReferenceError 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:

  1. If Type(val) is Reference, then

    a. If IsUnresolvableReference(val) is true, return "undefined".

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375