Once upon a time in the land of Codeville, there lived two friends, Jagroop π§βπ» and Manish π©βπ». Both were JavaScript developers, but they had very different styles of declaring variables and functions. One day, they embarked on a journey to debug an issue with their magical spells... err, code.
The Mysterious Bug π€
Jagroop had written this code:
console.log(wizard); // What could this be?
var wizard = "Gandalf";
Manish's curious eyes widened. "Jagroop! You're trying to summon a wizard before declaring it!" he exclaimed. But to his surprise, the output wasnβt an error but undefined
. π€―
The Wise Old Interpreter π§ββοΈ
The JavaScript interpreter appeared out of nowhere and said, "Young coders, this phenomenon is called hoisting. In JavaScript, declarations of variables and functions are magically moved to the top of their scope during the compile phase."
He demonstrated:
// How JavaScript sees Jagroop's code:
var wizard;
console.log(wizard); // undefined
wizard = "Gandalf";
The Function Spell β¨
Jagroop tried his luck with a function:
greet(); // "Hello, Codeville!"
function greet() {
console.log("Hello, Codeville!");
}
Manish clapped in awe. "Wow, it works even though you called it before declaring it!"
The interpreter explained, "Functions are also hoisted. But hereβs the catch: entire function definitions are hoisted, not just their declarations. That's why your function works."
An Evil Trap π
But then Jagroop got overly confident and wrote this:
console.log(villain); // π€·ββοΈ undefined
var villain = "Sauron";
console.log(sidekick); // π¨ ReferenceError
let sidekick = "Samwise";
The interpreter sighed and said, "Not all declarations behave the same. let
and const
are hoisted, but they donβt get initialized until the code execution reaches them. This is called the Temporal Dead Zone (TDZ)."
The Moral of the Story π°
Manish decided to summarize their learnings:
-
var
declarations are hoisted and initialized toundefined
. - Function declarations are fully hoisted (you can call them before declaring).
-
let
andconst
declarations are hoisted but stay in the TDZ until initialized.
The Wizard's Challenge π§ββοΈβ
Hereβs a puzzle for you, young coder! What will be the output of this code?
function test() {
console.log(hero); // ?
console.log(villain); // ?
var hero = "Sauron";
let villain = "Samwise";
}
test();
Drop your answers in the comments! πβ¨
Top comments (5)
It's output is
Correct !!
Wow the concept of
hoisting
is explained in such a good story.This make easier to learn the concept.Nice explanation of hoisting concept.
Thanks@hraifi