The output was undefined as the variable got hosted. Whereas here, the output will get printed:
Now take a look here:
Here, we see a change instead of getting undefined, we got Uncaught Reference Error.
let was introduced in ES6 and doesn't allow the use of undeclared variables, the interpreter explicitly throws out a Reference error.
var vs let
let is block-scoped and has been introduced as part of ES6. Variables will get hoisted using this but not initialized.
Temporal Dead Zone
The time span when that happens, between the creation of a variable’s binding and its declaration, is called the temporal dead zone.
Execution Context Phases
- Memory Allocation Phase (Variable Environment)
- Code Execution Phase (Thread of Execution)
Memory Allocation Phase
In the first phase, the entire program is skimmed line by line and memory is allocated to functions and variables. In the case of variables, undefined is stored as a placeholder and in the case of functions, the whole code of the function is stored.
Code Execution Phase
In the second phase, the code is actually executed line by line. The undefined keyword is now replaced by actual values of variables. When there is a function invocation, an entirely new execution context is created which has further two components. When the return keyword is encountered, it just returns all the controls to the global execution context where the function was first invoked. After the complete execution of a function, the execution context related to the instance of the function is deleted. Then, the next line is executed.
So when, variables are accessed before their initialization (second phase), simply undefined is printed. In case, if the variable is deleted later, an Uncaught Reference Error is thrown saying the variable was not defined. There is a huge difference between not defined and undefined.
When functions are accessed before their initialization (second phase), their output is printed as in the first phase their entire code is stored.
For more information, you can refer here.