Basically, the typeof
operator checks whether a variable1 is unresolvable and returns "undefined"
. That is, typeof
returns a defined value for undeclared variables1 before reaching the GetValue
algorithm which throws for undeclared variables1.
Quoting ECMAScript 5.1 § 11.4.3 The typeof Operator (emphasis added):
11.4.3 The typeof Operator
The production UnaryExpression : typeof
UnaryExpression is
evaluated as follows:
- Let val be the result of evaluating UnaryExpression.
If Type(val) is Reference, then
2.1. If IsUnresolvableReference(val) is true
, return "undefined"
.
2.2 Let val be GetValue(val).
Return a String determined by Type(val) according to Table 20.
In the other hand, the return statement -- like most operators and statements which read the value from identifier(s) -- will always call GetValue
which throws on unresolvable identifiers (undeclared variables). Quoting ECMAScript 5.1 § 8.7.1 GetValue (V) (emphasis added):
8.7.1 GetValue (V)
- If Type(V) is not Reference, return V.
- Let base be the result of calling GetBase(V).
- If IsUnresolvableReference(V), throw a
ReferenceError
exception.
Now, analyzing the code:
typeof (function() { return foo; })()
This code will instantiate a function object, execute it and only then typeof
will operate on the function's return value (function call takes precedence over the typeof
operator).
Hence, the code throws while evaluating the IIFE's return
statement, before the typeof
operation can be evaluated.
A similar but simpler example:
typeof (foo+1)
The addition is evaluated before typeof
. This will throw an error when the Addition Operator calls GetValue
on foo
, before typeof
comes into play.
Now:
typeof (foo)
Does not throw an error as the grouping operator (parentheses) does not "evaluate" anything per se, it just forces precedence. More specifically, the grouping operator does not call GetValue
. In the example above it returns an (unresolvable) Reference.
The annotated ES5.1 spec even adds a note about this:
NOTE This algorithm does not apply GetValue
to the result of evaluating Expression. The principal motivation for this is so that operators such as delete
and typeof
may be applied to parenthesised expressions.
N.B. I've wrote this answer with the focus on providing a simple and understandable explanation, keeping the technical jargon to a minimum while still being sufficiently clear and providing the requested ECMAScript standard references, which I hope to be a helpful resource to developers who struggle with understanding the typeof
operator.
1 The term "variable" is used for ease of understanding. A more correct term would be identifier, which can be introduced into a Lexical Environment not only through variable declarations, but also function declarations, formal parameters, calling a function (arguments
), with
/catch
blocks, assigning a property to the global object, let
and const
statements (ES6), and possibly a few other ways.