Home
JavaScript
JavaScript Hoisting
April 11, 2024
1 min

Table Of Contents

01
Variable Hoisting
02
Function Hoisting
03
Quick Comparison

Hoisting is JavaScript’s behavior of moving declarations to the top of their scope during the compile phase. This doesn’t mean code is physically moved—JavaScript just knows about certain variables and functions before execution starts.

Variable Hoisting

var

  • Hoisted and initialized to undefined
  • Accessible before declaration (but value is undefined)
  • Function-scoped (not block-scoped)
console.log(a); // undefined
var a = 10;

⚠️ This can cause subtle bugs because accessing a before assignment doesn’t throw an error.

let

  • Hoisted but NOT initialized
  • Exists in the Temporal Dead Zone (TDZ) until declared
  • Block-scoped
console.log(b); // ❌ ReferenceError
let b = 10;

const

  • Same hoisting behavior as let
  • Must be initialized at declaration
  • Block-scoped and cannot be reassigned
console.log(c); // ❌ ReferenceError
const c = 10;

let and const are safer than var because they prevent early access.

Function Hoisting

Function Declarations

  • Fully hoisted (name + implementation)
  • Can be called before they appear in code
sayHello();
function sayHello() {
console.log("Hello!");
}

✔️ This works because the entire function is hoisted.

Function Expressions

  • Hoisting depends on how they’re declared

With var

sayHi(); // ❌ TypeError: sayHi is not a function
var sayHi = function () {
console.log("Hi");
};
  • Variable is hoisted as undefined
  • Function body is not hoisted

With let / const

sayHey(); // ❌ ReferenceError
const sayHey = function () {
console.log("Hey");
};
  • In TDZ until declaration
  • Safer and more predictable

Quick Comparison

DeclarationHoistedInitializedScopeSafe to Access Early
varundefinedFunction⚠️ Yes (but risky)
letBlock
constBlock
Function DeclarationFunction
Function ExpressionPartialDepends

Tags

#Javascript

Share

Related Posts

JavaScript
Debouncing vs Throttling
August 30, 2025
1 min
© 2026, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube