It is a spec exception to allow safe feature detection. typeof undeclared returns 'undefined' instead of throwing ReferenceError. This lets you check if a global API exists without crashing.
How the JavaScript Engine Resolves Variables
Why does typeof not throw for undeclared variables in JavaScript?
The answer
More FAQs in How the JavaScript Engine Resolves Variables
It checks the current lexical environment's environment record. If not found, it follows the outer reference to the parent environment and repeats. This continues up to the global scope. If not found, it throws ReferenceError.
In sloppy (non-strict) mode, it creates a global property on window. In strict mode (and ES modules), it throws ReferenceError. Always use strict mode to catch this bug.
ReferenceError: Cannot access 'x' before initialization. The variable is in the environment record but marked as uninitialized until the declaration line.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.