Function Hoisting in JS

pushpesh kumarpushpesh kumar
2 min read

What is Hoisting?

Hoisting is a JavaScript mechanism where variable and function declarations are moved (“hoisted”) to the top of their scope before execution. It’s not magic—it’s how the JS engine sets up memory during the creation phase od execution context.


🧩 How It Works

Two Phases of Execution Context:

  1. Creation Phase

    • JavaScript scans for all var variables and function declarations.

    • These names are registered in memory: var variables are initialized as undefined, and function declarations are fully hoisted.

  2. Execution Phase

    • The code runs line by line, assigning values and executing functions.

🔄 In this article we will look into function hoisting in detail.

✅ Function Declaration

// Here we see a function being hoisted
// Here a function is declared in the global scope but since it is hoisted we can call the function even before the function declaration
f();
function f() {
  console.log("I am hoisted");
}
console.log("----------------------");
// Here we could call f1 before its declaration due to hoisting
f1();
function f1() {
  console.log("I am function f1");

  function f2() {
    console.log("I am nested function inside f1");
  }
  f2();
}
console.log("----------------------");

f3();
// f4(); we get error f4 is not defined because f4 is not hoisted at the top of global scope
function f3() {
  console.log("I am function f3");

  function f4() {
    console.log("I am nested function inside  f3");
  }
}
console.log("----------------------");

// Since f6 is hoisted inside f5 it is possible to call f6 before its declaration
f5();
function f5() {
  console.log("I am function f5");
  f6();

  function f6() {
    console.log("I am nested function inside f5");
  }
}

console.log("----------------------");

// x(); TypeError: x is not a function . This happens because variable x is hoisted with value undefined
var x = function () {
  console.log("I am a ");
};

// functions created with function expressions cannot be "used" before their initialization.
// y(); ReferenceError: Cannot access 'y' before initialization
const y = function () {
  console.log("I can not be called before initialization");
};

// z(); ReferenceError: Cannot access 'z' before initialization. This happens because z is defined using let keyword and it is hoisted but remains in TDZ untill declared
let z = () => {
  console.log("I can not be called before initialization");
};
0
Subscribe to my newsletter

Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

pushpesh kumar
pushpesh kumar