šŸš€ AI SaaS Starter is now live!

50% OFF

Use code FIRST50

Blog/NotesConcept

Master Hoisting in JavaScript with 5 Examples

Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.

Intermediate

Alok Kumar Giri

Last Updated Jun 2, 2025


Understanding hoisting in JavaScript is important to understand how the variables and function scope behave in different scenarios. There are different scenarios where hoisting behaves differently than anticipated, which makes hoisting a favourite topic for Frontend Interviews.

In this post, we have curated 5 examples with detailed explanations which cover important scenarios to understand hoisting in depth. šŸ‘‡

Jump to the examples

  1. Example 1: Overshadow variable
  2. Example 2: Hoisting with different variable types
  3. Example 3: Function Hoisting
  4. Example 4: Methods Hoisting
  5. Example 5: Variable hoisting with inner functions

Example 1: Overshadow variable

Guess the output of the code snippet below
var foo = 'LION';

function showName(){
    foo = 'PANDA';
    return;
    function foo(){};
};
showName();  // Guess o/p
console.log(foo); // Guess o/p

Solution:

The code will undergo two phases:
  1. Memory Phase
  2. Execution Phase

In Memory phase

function showName(){  // Function declaration is hoisted to the top of their scope with its entire function body. Since showName() is in the global scope, it’s hoisted to the top of the global scope.
    function foo(){};      // As mentioned above, it is hoisted to the top its scope. In this case, in the function scope showName() along with its entire function body. So, foo becomes the local variable of type 'function'.
    foo = 'PANDA';       
    return;
};
var foo = undefined;   // Only the declaration of 'var' is attached to the global scope with default initialization to 'undefined'. 

Note: "During hoisting, JavaScript places function declarations like function showName() { ... } in memory before any var declarations, even if the var appears earlier in the source code."


In the Execution Phase

showName(); // Runs, but only changes local `foo` to PANDA
console.log(foo); // LION

Explanation:

In the execution phase, var foo is re-initialised to 'LION' and in the execution of the function showName(), the function, foo(){} as hoisted to the top of its function body, will be overridden by the next line's foo variable with value 'PANDA', this foo becomes a local variable. Thus, on the console, we see 'LION' for foo.

Example 2: Hoisting with different variable types

Guess the output of the code snippet below

console.log(a); // Guess o/p
console.log(b); // Guess o/p
console.log(c); // Guess o/p

var a = 10;
let b = 20;
const c = 30;

Solution:

The code will undergo two phases:

  1. Memory Phase
  2. Execution Phase

In Memory Phase

  • a (declared with var) is hoisted and initialized to undefined.

  • b (with let) is hoisted but in TDZ(Temporal Dead Zone) (not initialized yet).

  • c (with const) is hoisted but in TDZ (not initialised yet).

In the Execution Phase

/*
Output: undefined → Because a is hoisted and initialised to undefined.
*/
console.log(a);

/*
Output: Throws ReferenceError → b is in the Temporal Dead Zone (TDZ), 
so any access before declaration throws a ReferenceError.
*/
console.log(b);

/*
Never Executed as console.log(b) already throws the ReferenceError, 
but if console.log(b) is commented, then this too shall throw ReferenceError → c is in the Temporal Dead Zone (TDZ).
*/
console.log(c); // 

var a = 10;
let b = 20;
const c = 30;

Notes: 

  1. The Temporal Dead Zone is the period between: When a let or const variable is hoisted to the top of its scope and when the variable is actually declared (initialized) in the code. During this time, the variable exists in memory, but you cannot access it — doing so will throw a ReferenceError. 

  2. Why is it called "Dead Zone"? : Because although the variable is technically hoisted, it's in a state where it's "not alive" (usable) yet. Trying to use it before its declaration is like trying to drink from an empty cup that hasn’t even been filled yet šŸ˜….

Example 3: Function Hoisting

Guess the output of the code snippet below:

greet(); // Guess the O/P
shout(); // Guess the O/P
whisper(); // Guess the O/P

function greet() {
  console.log("Hello from greet()");
}

var shout = () => {
  console.log("Hello from shout()");
};

let whisper = () => {
  console.log("Hello from whisper()");
};

Solution:

The code will undergo two phases:
  1. Memory Phase
  2. Execution Phase
In Memory Creation Phase
// A function declared as a function declaration, the entire function is hoisted to the top of the scope.
greet → function() { console.log("Hello from greet()") }

// As this function is declared using 'var'
shout   → undefined

// As declared using 'let'
whisper  → TDZ (not initialized yet)

 

In the Execution Phase

/*
āœ… Output: Hello from greet()
*/
greet();

/*
āŒ TypeError: shout is not a function → 
This would NOT be hoisted the same way — only the greet variable would be hoisted as 'undefined', 
not the function body. So calling greet() before this line would give you a TypeError.
*/
shout();

/*
Never Executed as shout() shall throw an error before but if shout() is commented, 
then → āŒ ReferenceError: Cannot access 'whisper' before initialization
*/
whisper();


function greet() {
  console.log("Hello from greet()");
}

var shout = () => {
  console.log("Hello from shout()");
};

let whisper = () => {
  console.log("Hello from whisper()");
};

Example 4: Methods Hoisting

Guess the output of the code snippet below:

console.log(myObjA.sayHello()); // Guess the O/p
console.log(myObjB.sayHello()); // Guess the O/p

var myObjA = {
  sayHello: function () {
    return "Hello!";
  }
};

const myObjB = {
  sayHello: function () {
    return "Hello!";
  }
};

Solution:

The code will undergo two phases:
  1. The Memory Phase
  2. The Execution Phase

In Memory Creation Phase

myObjA = undefined

var myObj is hoisted and initialized with 'undefined'. Here, the object literal { sayHello: function() { ... } } is not assigned yet. Therefore, no function named sayHello exists independently in memory.

myObjB is in TDZ (Temporal Dead Zone)

const and let variables go into the Temporal Dead Zone (TDZ) — they’re not accessible until the engine reaches the declaration line.

 In the Execution Phase

/*
āŒ TypeError: myObjA.sayHello is not a function. 
When JS engine sees console.log(myObj.sayHello()), 
myObjA is 'undefined' at that point (assignment hasn’t happened yet) 
and thus, trying to access sayHello from undefined throws an error.
*/
console.log(myObjA.sayHello());

/*
āŒ ReferenceError: Cannot access 'myObjB' before initialization. 
When JS engine tries to run: 
*/
console.log(myObjB.sayHello()); 

/*
Since myObjB is still in the TDZ, a ReferenceError is thrown.
*/
console.log(myObjB.sayHello())

var myObjA = {
  sayHello: function () {
    return "Hello!";
  }
};

const myObjB = {
  sayHello: function () {
    return "Hello!";
  }
};

Example 5: Variable hoisting with inner functions

Guess the output of the code snippet below:
var globalVar = "I am Global";

function outerFunction() {
  var outerVar = "I am Outer";

  function innerFunction() {
    console.log(globalVar);  // Guess the O/P
    console.log(outerVar);   // Guess the O/P
  }

  innerFunction();
}

outerFunction();

Solution:

The code will undergo two phases:
  1. The Memory Phase
  2. The Execution Phase

In Memory Creation Phase

  1. globalVar is declared and initialized with 'undefined'.

  2. outerFunction being a 'function declaration' is hoisted as a complete function (its definition is available in memory)
  3. Inside outerFunction, outerVar and innerFunction are prepared in memory when outerFunction gets invoked (not before).
  4. outerVar → 'undefined' initially (before outerFunction's code runs)
  5. innerFunctionwhole function stored (just like normal function hoisting inside a function).
In Execution Phase
  1. outerFunction() is called.
  2. Inside outerFunction:

    • outerVar is assigned "I am Outer".

    • innerFunction is called.

  3. Inside innerFunction:

    • It looks for globalVar. Not found inside itself → goes to outer scopes → finds it in global → logs "I am Global".

    • It looks for outerVar. Found in outerFunction's local memory → logs "I am Outer".

var globalVar = "I am Global";

function outerFunction() {
  var outerVar = "I am Outer";

  function innerFunction() {
    console.log(globalVar);  // I am Global
    console.log(outerVar);   // I am Outer
  }

  innerFunction();
}

outerFunction();
I hope this helps increase your understanding of Hoisting in JavaScript by covering different scenarios and helps you to better handle output-based questions related to hoisting.

ā© Next Read

  1. 5 Ultimate Rules to master this keyword in JavaScript
  2. What is Throttling in JavaScript - Implementation & Examples

šŸš€

Love this content? Share it!

Help others discover this resource

Comments

Be the first to share your thoughts!

Guest User

Please login to comment

0 characters


No comments yet.

Start the conversation!

Share Your Expertise & Help the Community!

Build Your Portfolio

Help the Community

Strengthen Your Skills

Share your knowledge by writing a blog or quick notes. Your contribution can help thousands of frontend developers ace their interviews and grow their careers! šŸš€


Other Related Blogs

Top 10 React Performance Optimization Techniques [React Interview]

Anuj Sharma

Last Updated Nov 10, 2025

Find the top React Performance Optimization Techniques specific to React applications that help to make your react app faster and more responsive for the users along with some bonus techniques.

Polyfill for map, filter, and reduce in JavaScript

Anuj Sharma

Last Updated Oct 2, 2025

Explore Polyfill for map, filter and reduce array methods in JavaScript. A detailed explanation of Map, filter and reduce polyfills in JS helps you to know the internal working of these array methods.

Implement useFetch() Custom Hook in React (Interview)

Anuj Sharma

Last Updated Nov 23, 2025

Find the step-by-step explanation of the useFetch custom hook in React that helps in fetching the data from an API and handling loading, error states.

Flatten Nested Array in JavaScript using Recursion

Anuj Sharma

Last Updated Nov 24, 2025

Understand step by step how to flatten nested array in javascript using recursion, also explore the flatten of complex array of object.

Implement useThrottle Custom Hook In React (Interview)

Anuj Sharma

Last Updated Nov 23, 2025

Implement useThrottle Custom Hook In React (Interview) to limit the number of APi calls to improve the performance of application.

Implement useToggle() Custom Hook in React (Interview)

Anuj Sharma

Last Updated Nov 23, 2025

Explore code explanation of useToggle() custom hook in react to handle the toggle event efficiently.

Stay Updated

Subscribe to FrontendGeek Hub for frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

Ā© 2025 FrontendGeek. All rights reserved