Hoisting

20 Oct 2023 . javascript .

  • Variables declared or intialized with the var keyword will have their declaration “moved” up to the top of their module/function-level scope, which we refer to as hoisting. However, only the declareation is hoisted, the assignment will stay where it is.
console.log(foo); // undefined
var foo = 1;
console.log(foo); // 1
  • Function declarations have the body hoisted while the function expressions(written in the form of variable declarations) only has the variable declaration hoisted.
// Function Declaration
console.log(foo); // [Function: foo]
foo(); // 'FOOOOO'
function foo() {
  console.log('FOOOOO');
}
console.log(foo); // [Function: foo]

// Function Expression
console.log(bar); // undefined
bar(); // Uncaught TypeError: bar is not a function
var bar = function () {
  console.log('BARRRR');
};
console.log(bar); // [Function: bar]
  • Variables declared via let and const are hoisted as well. However, unlike var and function, the variable is in a temporal dead zone.
x; // undefined
y; // Reference error: y is not defined

var x = 'local';
let y = 'local';

Temporal dead zone(TDZ)

A let or const variable is said to be in a TDZ from the start of the block until code execution reaches the line where the variable is declared and intitialized.

While inside the TDZ, the variable has not been initialized with a value, and any attempt to access it will result in a ReferenceError. The variable is intitialized with a value when execution reaches the line of code where it was declared.