let and const Keywords Hoisting

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 with var, is hoisted and attached to the global object (e.g., window in browsers).
  • The variable b, declared with let, is hoisted but resides in the block scope and cannot be accessed until it is initialized. Attempting to access it beforehand results in a ReferenceError.

When you run the example, you’ll notice:

  • Memory for a is allocated in the global object (window in browsers).
  • Memory for b is allocated in a separate script scope 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 var are hoisted and initialized with undefined.
  • Variables declared with let and const are hoisted but remain uninitialized, existing in the temporal dead zone until their declaration is encountered.
  • Attempting to access let variables before declaration results in a ReferenceError.
  • Attempting to access const variables before declaration results in a SyntaxError.

References

w3schools

Read More