Javascript
Hoisting

Hoisting

It is a term used to explain the behaviour of variable declarations in our code.

when var is used to declare a variable, it is hoisted (moved up) to the top of its scope, hovever only the declaration is hoisting, assignment stays.

  • this is because the Javascript engine parses the declarations during compilation, and the assignments at runtime.
console.log(foo); // undefined
var foo = 1;
console.log(foo); // 1

Function declarations are also hoisted but their function expressions only has their 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 with let and const are hoisted but unlike var they are not initialized to undefined. They are in a state called "temporal dead zone" where they are not accessible.

foo; // undefined
bar; // ReferenceError: bar is not defined
 
var foo = "hello";
let bar = "world";

References