JavaScript Hoisting Cheatsheet
š£ 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 type | Hoisted | Initialized |
|---|---|---|
var | Yes | undefined |
let | Yes | No |
const | Yes | No |
| Function declaration | Yes | Fully |
| Function expression | No | No |
| Class declaration | Yes | No |
var hoisting
var declarations are hoisted and initialized with undefined.
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:
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.
console.log(name); // ā ReferenceError
let name = "Ada";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.
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.
greet(); // ā TypeError: greet is not a function
var greet = function () {
console.log("Hi");
};Arrow functions behave the same way.
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.
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.
console.log(example); // [Function: example]
var example = 1;
function example() {
console.log("I am a function");
}
console.log(example); // 1Avoid 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.
