Skip to content
Shubham JangleResources
JavaScript

Explore topics

What is hoisting

Watch the walkthrough
Open on Instagram

Revision clarifications

Hoisting describes declaration setup, not literal movement of source lines. The temporal dead zone starts on entering the scope and ends at initialization. Function expressions follow the rules of their variable binding.

The source notes below are copied unchanged apart from line endings. Examples are independent; some deliberately throw or depend on browser markup.

Original HackTheCode notes

Read the original Markdown

Hoisting is a mechanism in JavaScript that moves all variable and function declarations to the top of their scope before code execution. This means that a variable or function can be used before it has been declared.

  • var: only declaration hoisted
  • let and const: Declarations hoisted but not initialized, leading to a temporal dead zone (this is the period between variable declaration and the initialization).
  • Functions: Function declarations are fully hoisted, except functions initializations.
console.log(dog); // undefined
var dog = "🐢"; // var
console.log(dog); // "🐢"
console.log(rabbit); // ReferenceError: Cannot access 'rabbit' before initialization
let rabbit = "πŸ‡"; // let
console.log(rabbit); // "πŸ‡"
console.log(her); // ReferenceError: Cannot access 'her' before initialization
const her = "πŸ’ƒ"; // const
console.log(her); // "πŸ’ƒ"
console.log(foo()); // "Hello, world!"

function foo() {
  return "Hello, world!";
}
console.log(car()); // TypeError: car is not a function

var car = function () {
  return "πŸš— Starting!";
};

console.log(car()); // "πŸš— Starting!"