constkeywords. This is not applicable to
console.log(message); var message = "Roses are red, violets are blue"; // undefined
The output is
var message; console.log(message); message = "Roses are red, violets are blue";
- compile time: run through all code looking for variable/function declarations
- runtime: execute the code including assignments and function invocations
That's the reason
undefined to the variables that are defined but not assigned with a value. Therefore, the result of line 2 will be undefined because the assignment occurs in line 3.
But if we use
const keywords to declare the variable, the same code will throw an error:
console.log(message); let message = "Roses are red, violets are blue"; // ReferenceError: message is not defined
console.log(message); const message = "Roses are red, violets are blue"; // ReferenceError: message is not defined
So why we get the Reference error here? Because the variables are unreachable. They are in the scope, but are not declared. They are in a temporal dead zone.
The time span when that happens (Reference error), between the creation of a variable's binding and its declaration, is called the temporal dead zone.
-Dr. Alex Rauschmayer
Temporal dead zone exists to catch the programming errors. It is normally by accident that one tries to access variables before its declaration and therefore, one should be warned about it.
const keywords get hoisted, but are not assigned
undefined value. Best practice to make TDZ zero for variables in a program is to declare all the variables at the top of its scope.