Skip to content

Latest commit

 

History

History
69 lines (45 loc) · 1.88 KB

File metadata and controls

69 lines (45 loc) · 1.88 KB

03 Hoisting

Hoisting is a JavaScript behavior where variable and function declarations are processed before code execution begins.

03.1 Variable Hoisting

The behavior of hoisting depends on how the variable is declared.

03.1.1 var Hoisting

Variables declared with var are hoisted and initialized with undefined.

console.log(a); // undefined
var a = 10;

03.1.2 let and const Hoisting

Variables declared with let and const are hoisted but not initialized. Accessing them before declaration results in an error due to the Temporal Dead Zone (TDZ).

console.log(b); // ReferenceError
let b = 20;

Note: The Temporal Dead Zone is the time between entering a scope and declaring the variable, during which the variable cannot be accessed.

03.2 Function Hoisting

03.2.1 Function Declaration

Function declarations are fully hoisted, meaning they can be called before they are defined.

greet();

function greet() {
  console.log("Hola!");
}

03.2.2 Function Expression

Function expressions are not hoisted the same way. If assigned to var, only the variable is hoisted.

sayHi(); // TypeError

var sayHi = function () {
  console.log("Hi");
};
Problems Caused by Hoisting
  • Accessing variables before declaration can cause unexpected bugs
  • var hoisting can silently return undefined
  • let and const can throw ReferenceError due to TDZ
  • Function expressions may cause TypeError if called early
Solutions and Best Practices
  • Always declare variables at the top of their scope
  • Prefer let and const over var
  • Avoid using variables before they are declared
  • Use function declarations when hoisting behavior is required

Note: Understanding hoisting helps you write predictable code and avoid runtime errors, especially when working with larger codebases.