Preparation
πŸ’‘ ⏐ JavaScript Questions
7. Hoisting, TDZ

Hoisting, Temporal Dead Zone

Understanding hoisting and the temporal dead zone (TDZ) in JavaScript is essential for comprehending how variable declarations are processed during runtime. Let's explore these concepts:

πŸ”₯ Hoisting

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during compilation. However, only the declarations are hoisted, not the initializations.

console.log(count); // undefined
var count = 1;
 
// console.log(count2); // Cannot access 'count2' before initialization
let count2 = 2;

In the example above, count is declared using var, so it is hoisted to the top of the scope. However, since there's no initialization (count = 1;) until after the console.log statement, accessing count will result in undefined.

πŸ”₯ Temporal Dead Zone (TDZ)

The Temporal Dead Zone (TDZ) is the period between entering scope and variable declaration. During this time, accessing variables declared with let and const will result in a ReferenceError.

CARS24 interview question related to Hoisting

What is the output for console log a ??

function abc() {
  console.log(a, b, c, ">>>>>>"); // undefined , Cannot access 'b' before initialization
 
  const c = 30;
  let b = 20;
  var a = 10;
}
 
abc();

In the abc() function, a is declared using var, b is declared using let, and c is declared using const. Within the console.log statement, a, b, and c are referenced. However, at the time of the console.log statement, a is hoisted (initialized with undefined), but b and c are still in the Temporal Dead Zone (TDZ), hence accessing them results in an error. Therefore, the output for console.log(a, b, c, ">>>>>>"); would be undefined , Cannot access 'b' before initialization.

Conclusion

  • Hoisting moves variable and function declarations to the top of their containing scope during the compile phase.
  • Hoisting applies to both variables declared with var and function declarations.
  • The temporal dead zone (TDZ) prevents accessing let and const variables before their initialization, promoting safer and more predictable code.
  • Understanding hoisting and the TDZ helps in writing cleaner, more robust JavaScript code by avoiding common pitfalls associated with variable declarations and scoping.