In JavaScript, declarations are hoisted. Variables declared using let and const are hoisted to the top of their block scope but are not initialized. While the block is aware of the variable, it cannot be used until after it has been declared. This period is known as the temporal dead zone—the time between the start of the block and the point where 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
In the example above:
- The variable
a, declared withvar, is hoisted and attached to the global object (e.g.,windowin browsers). - The variable
b, declared withlet, is hoisted but resides in the block scope and cannot be accessed until it is initialized. Attempting to access it beforehand results in aReferenceError.
When you run the example, you’ll notice:
- Memory for
ais allocated in the global object (windowin browsers). - Memory for
bis allocated in a separatescriptscope and is inaccessible until the variable is initialized.
Common errors with let and const
Using let before declaration
Attempting to use a let variable before its declaration results in a ReferenceError.
carName = "Volvo";
let carName;
// Uncaught ReferenceError: Cannot access 'carName' before initialization
Using const before declaration
Using a const variable before its declaration results in a SyntaxError, preventing the code from running altogether.
carName = "Volvo";
const carName;
// SyntaxError: Missing initializer in const declaration
Summary
- Variables declared with
varare hoisted and initialized withundefined. - Variables declared with
letandconstare hoisted but remain uninitialized, existing in the temporal dead zone until their declaration is encountered. - Attempting to access
letvariables before declaration results in aReferenceError. - Attempting to access
constvariables before declaration results in aSyntaxError.
What are your thoughts on this post?
I’d love to hear from you! Click this link to email me, I reply to every message!
Also use the share button below if you liked this post. It makes me smile, when I see it.