Hoisting
Floating Zen Lanterns
Imagine a tranquil Zen garden at twilight, where floating lanterns light the path before the night fully descends. This garden, representing the scope of a JavaScript function, is adorned with lanterns (variables and functions) that begin to float and illuminate (hoist) before the darkness (code execution) sets in. Just as these lanterns are already in their positions, casting light on the paths below, JavaScript variables and functions are accessible in their scope before the code runs. This pre-illumination is akin to hoisting, where the declarations (lanterns) are considered to exist and illuminate from the top of their environment (garden) even before the night (code execution) fully arrives.
Twilight Prelude
Lanterns float aloft,
Before night whispers to day,
Hoisting light to dark.
Illuminating the Zen Path
// Before the night fully descends (execution), the lantern (function) is already alight (hoisted)
guidePath("lantern");
// Function declaration: lights the way in the Zen garden
function guidePath(lantern) {
console.log(`The floating ${lantern} guides the way through the twilight.`);
}
// Variable declaration: known but not defined until nightfall (execution)
console.log(zenLantern); // undefined due to hoisting
var zenLantern = "floating lantern";
// After being lit, the lantern illuminates the path
console.log(zenLantern); // "floating lantern"
This code demonstrates how, akin to lanterns that float and light up before darkness, function and variable declarations in JavaScript are hoisted and accessible in their scope before the code is executed. The function guidePath
is callable before its declaration in the script, illustrating how JavaScript prepares its functions and variables (lanterns) ahead of time, allowing them to illuminate (be used) even if they're officially defined later in the code.
Hoisting
Harmoniously Organizing Initial Symbols Towards Inception's Nadir Gracefully - HOISTING
A way to remember that hoisting organizes declarations at the top before execution.
Concept Checking Questions
-
What does hoisting do in JavaScript?
- Hoisting moves declarations to the top of their scope before code execution.
-
Can you use a variable before it's declared due to hoisting?
- Yes, but it will be
undefined
until its declaration is reached and initialized.
- Yes, but it will be
-
Is there a difference in hoisting between
var
,let
, andconst
?- Yes. While
var
declarations are hoisted and initialized withundefined
,let
andconst
are hoisted but not initialized, leading to a Temporal Dead Zone until their declaration line is executed.
- Yes. While