ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript Hoisting Cheatsheet

@thedevspaceio

šŸ“£ JavaScript Hoisting Cheatsheet

Hoisting moves declarations to the top of their scope before execution, affecting how var, let, const, functions, and classes behave.

āœ… var hoisting āœ… let and const hoisting āœ… Function declarations āœ… Function expressions āœ… Class declarations āœ… Order of precedence

#javascript #hoisting #scope #tdz #variables #functions #webdev #frontend #coding #tips


Hoisting moves declarations to the top of their scope before code execution. Only declarations are hoisted, not initializations.

Declaration typeHoistedInitialized
varYesundefined
letYesNo
constYesNo
Function declarationYesFully
Function expressionNoNo
Class declarationYesNo

var hoisting

var declarations are hoisted and initialized with undefined.

js
console.log(message); // undefined
var message = "Hello";
console.log(message); // "Hello"

When you move the declaration to the top, but the assignment stays in place:

js
var message;
console.log(message); // undefined
message = "Hello";
console.log(message); // "Hello"

let and const hoisting

let and const are hoisted but remain in the temporal dead zone until their declaration line executes.

js
console.log(name); // āŒ ReferenceError
let name = "Ada";
js
console.log(PI); // āŒ ReferenceError
const PI = 3.14;

The temporal dead zone is the region between the start of the scope and the declaration.


Function declarations

Function declarations are fully hoisted, so you can call them before they appear in code.

js
sayHello(); // "Hello"
 
function sayHello() {
  console.log("Hello");
}

Function expressions

Function expressions are not hoisted as functions. If declared with var, the variable is hoisted as undefined.

js
greet(); // āŒ TypeError: greet is not a function
var greet = function () {
  console.log("Hi");
};

Arrow functions behave the same way.

js
add(1, 2); // āŒ TypeError
const add = (a, b) => a + b;

Class declarations

Class declarations are hoisted but not initialized. Accessing them before the declaration throws a ReferenceError.

js
const user = new User("Ada"); // ReferenceError
 
class User {
  constructor(name) {
    this.name = name;
  }
}
 
const user = new User("Ada");

Order of precedence

Variable declarations and function declarations can conflict. Function declarations are hoisted first, then variable declarations.

js
console.log(example); // [Function: example]
 
var example = 1;
 
function example() {
  console.log("I am a function");
}
 
console.log(example); // 1

hoisting order

Avoid mixing variable and function names to prevent confusion.

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io