Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.
Alok Kumar Giri
Last Updated Apr 28, 2025
Advertisement
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
var foo = 'LION';
function showName(){
foo = 'PANDA';
return;
function foo(){};
};
showName();
console.log(foo); // Guess o/p
In Memory phase
function showName(){ // Note: Entire function rose up
function foo(){}; // Note: Internally, the function foo() rose up
foo = 'PANDA'; // Note: Internally, this line of code rose up
return;
};
var foo = undefined; // Note: This line of code came below
In the Execution Phase
foo = 'LION';
showName();
console.log(foo);
Explanation:
In the memory phase, at first, the function declaration will be hoisted to the top of the global scope. And second to that, the variable var
will be hoisted with the value undefined
And within the function showName()
. The body function-declaration foo() will be hoisted to the top of its function body.
foo(){}
as hoisted to the top, 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.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;
The code will undergo two phases:
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:
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.
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()");
};
// 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()");
};
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!";
}
};
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.
/*
ā 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!";
}
};
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();
globalVar is declared and initialized with 'undefined'.
outerFunction
being a 'function declaration' is hoisted as a complete function (its definition is available in memory)outerFunction
, outerVar
and innerFunction
are prepared in memory when outerFunction
gets invoked (not before).outerVar
→ 'undefined' initially (before outerFunction's code runs)innerFunction
→ whole function stored (just like normal function hoisting inside a function).outerFunction()
is called.Inside outerFunction
:
outerVar
is assigned "I am Outer"
.
innerFunction
is called.
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();
Advertisement
Advertisement
Advertisement
Anuj Sharma
Last Updated Jan 9, 2025
Go through different ways to display dates using javascript date object. It covers examples of date object usage to understand the main concepts of javascript date object.
Anuj Sharma
Last Updated Jan 29, 2025
Understand the difference between HTTP/2 vs HTTP/1.1 based on the various parameters, which helps to understand the improvement areas of HTTP/2 over HTTP 1.1
Anuj Sharma
Last Updated Dec 10, 2024
A brief explanation of Cross-Origin Resource Sharing (CORS) concept to enable client application accessing resources from cross domain and HTTP headers involved to enable resource access.
Anuj Sharma
Last Updated Jan 16, 2025
Deep dive into promise.all polyfill in javascript will help to understand the working of parallel promise calls using Promise.all and its implementation to handle parallel async API calls.
Anuj Sharma
Last Updated Jan 9, 2025
Learn the best & quickest way to format phone number in JavaScript with or without country codes. This will help websites to show the phone numbers in a more human-readable format.
Anuj Sharma
Last Updated Jan 17, 2025
Explore the 5 most efficient ways to Refresh or Reload page in JavaScript similar to location.reload(true), and identify the appropriate use cases to use one of these different approaches.
Ā© 2024 FrontendGeek. All rights reserved