Sobes.tech
Middle

If you declare a function and then a variable after it, will it be accessible inside the function? Tell me about variable hoisting and the temporary dead zone.

sobes.tech AI

Answer from AI

In JavaScript, variables declared with var are hoisted — their declarations are moved to the top of the function or global scope, but initialization remains in place. Variables declared with let and const are also hoisted, but they are in a temporary dead zone (TDZ) from the start of the block until the declaration is encountered, and cannot be accessed before the declaration.

If a function is declared, and then a variable with let or const is declared after it, the variable will not be accessible inside the function before its declaration — attempting to access it will result in a ReferenceError due to TDZ.

Example:

function test() {
  console.log(a); // ReferenceError: Cannot access 'a' before initialization
  let a = 10;
}

test();

If the variable is declared with var, it will be accessible inside the function but will have the value undefined before initialization:

function test() {
  console.log(a); // undefined
  var a = 10;
}

test();

Thus, hoisting is the lifting of variable and function declarations to the top of their scope, but for let and const, the TDZ prevents access before declaration.

If you declare a function and then a variable after… - sobes.tech