JavaScript declarations are hoisted. Variables defined with let
and const
are hoisted to the top of the block, but not initialized. The block of code is aware of the variable, but it cannot be used until it has been declared. It is in the temporal dead zone
from the start of the block until it is declared. ( temporal dead zone is the time between the start of the code block until the variable is declared)
console.log(a); // undefined
console.log(b); // Uncaught ReferenceError: Cannot access 'b' before initialization
var a = 100;
let b = 1000;
console.log(window.a); // prints 100
If you run the above example you can see in the console, memory for a and b is defined, but the variable a
in Global object scope (in browser it is named as window
) and the let variable b is in the script section which you cann’t access till the variable intialization.
Using a let variable before it is declared will result in a ReferenceError.
carName = "Volvo";
let carName;
// Uncaught ReferenceError: Cannot access 'carName' before initialization
Using a const variable before it is declared, is a syntax errror, so the code will simply not run.
carName = "Volvo";
const carName;
// SyntaxError: Missing initializer in const declaration
Use the share button below if you liked it.
It makes me smile, when I see it.