JavaScript Hoisting
In JavaScript, hoisting is the automatic action of bringing declarations to the top by default.
JavaScript Declarations are Hoisted
In JavaScript, you can declare a variable even after using it.
Simply put, you can use a variable before officially stating it.
Example 1 gives the same result as Example 2:
To grasp this concept, it's essential to comprehend the term "hoisting."
In JavaScript, hoisting is the default way declarations are handled by moving them to the top of the current scope, whether it's the top of the script or the top of the function.
The let and const Keywords
Variables created using let
and const
are lifted to the beginning of the block, but they are not set to a value right away.
Explanation: A piece of code knows about the variable, but it can't be used until it's officially stated or declared.
If you try to use a variable with the let
keyword before declaring it, you'll get a ReferenceError
.
The variable stays in a 'temporal dead zone' from the beginning of the block until it gets declared:
If you try to use a const
variable before declaring it, it will result in a syntax error, and the code won't execute.
Learn more about let and const in JavaScript by visiting the JS Let / Const page.
JavaScript Initializations are Not Hoisted
In JavaScript, only declarations get moved to the top, not the initializations.
Example 1 does not give the same result asExample 2:
Is it clear why 'y' has no defined value in the final example?
The reason is that only the declaration (var y) is lifted to the top, not the initialization (=7).
Due to hoisting, 'y' is declared before it's used. However, since initializations aren't hoisted, the value of 'y' remains undefined.
Example 2 is the same as writing:
Declare Your Variables At the Top !
Many developers may not be familiar with or pay attention to hoisting in JavaScript.
If a programmer doesn't grasp hoisting, their code might have mistakes or errors.
To prevent errors, make sure to define all variables at the start of each section.
As JavaScript reads the code in this way, it's a smart practice to follow.
In strict mode, JavaScript doesn't let you use variables unless you declare them first.
Explore the concept of "use strict" in the upcoming chapter.