What is Hoisting in JavaScript?
What is hoisting in javascript? Hoisting in JavaScript is a fundamental concept that plays a crucial role in how variables and functions are executed within their respective scopes. This behavior allows developers to call functions and reference variables before they are explicitly defined in the script, leading to more flexible code organization.
Function Hoisting
We can use a function in our code before it is officially declared, making the sequence of function declarations less restrictive. Example
Output:
Explanation: The code looks as follows to the JS engine:
Explanation:
Creation Phase:
- The JavaScript engine scans the code during the creation phase.
- It recognizes the add function declaration and allocates memory for it.
- The console.log statement is also noted.
Execution Phase:
- The execution starts, and when the console.log is encountered, it sees the function add.
- Although the function is called before its declaration, the hoisting mechanism moves the function to the top during the creation phase.
- The function is available, and the output is 5, the result of add(2, 3).
In summary, even though the function is used before its actual declaration in the code, hoisting in javascript ensures that the function is accessible during the execution phase, producing the correct output of 5.
Variable Hoisting
Variable Hoisting, as its name implies, is the mechanism where Javascript moves the variable declarations to the top of the code. This is the type of Hoisting we have been discussing till now.
Example:
Output:
Explanation
The code looks as follows to the JS engine:
Hoisting var variables
Let's delve into the life cycle of variables declared with var to gain a more comprehensive understanding:
Example:
output:
Explanation:
- In the creation phase, the variable is declared, and it undergoes initialization with the value undefined.
- As the execution phase unfolds, the code is processed line by line. During this process, the variable temp is hoisted, printing undefined in the console.
- Subsequently, the value 2 is assigned to the variable during the execution phase.
Hoisting let variables
Let us look at the following code:
Output:
We got an error that we did not see in the previous examples. This is because var is both declared and initialized during hoisting, but let is not initialized, it is only declared. The variable is in a temporal dead zone(TDZ) till then.
Let us see the let variable lifecycle to understand this better:
Explanation:
- In the creation phase for variables declared with let, only declaration occurs with no initialization.
- A variable declared with let will be initialized only during the execution phase when the JS engine reaches the line with let keyword. At this point, it will be given the value undefined
- The temporal dead zone (TDZ) refers to the interval between the period when the variable exists in an uninitialized state and the moment it receives initialization.
- Following this phase, the assignment occurs, and the variable 'temp' is assigned the value "Scaler."
Hoisting const variables
const hoisting in javascript is the same as let hoisting except one difference. In let, the assignment happens after initialization. In const, the assignment and initialization happen together because once assigned, the value of const cannot change. If we assign undefined and then try to assign another value, the rule of const is violated.
Example:
Output:
)
Explanation:
- During the creation phase, variables declared with let receive memory allocation without initialization.
- For variables declared with const, initialization occurs only in the execution phase, precisely when the JS engine encounters the line containing the const keyword. At this juncture, assignment takes place, providing the variable with the declared value.
- The temporal dead zone (TDZ) denotes the period between the uninitialized state of a variable and the moment it undergoes initialization.
Class Hoisting
Unlike function declarations, classes in JavaScript are not hoisted. This means that you must declare a class before you can instantiate it. Attempting to use a class before its declaration results in a ReferenceError.
Example
Understanding the non-hoisting behavior of classes is crucial for JavaScript developers, as it influences the structure and order of your code.
Conclusion
- Javascript hoisting is a process where variables and function declarations are elevated to the top of their scope before code execution.
- Javascript hoisting allows accessing variables and functions even before they are formally declared, offering a significant advantage.
- It's important to note that function expressions and arrow functions do not undergo hoisting.
- The lifecycle of a variable involves three stages: Declaration, Initialization, and Assignment.
- While all variables in JavaScript experience hoisting, there are distinct methods for hoisting var variables compared to let and const variables.