Hoisting
Introduction
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope before code execution.
We can only hoisted var not const and let but let and const are also hoisted but kept in a special place called temporal dead zone. That means you cannot use them before you write them. if you used it will give the error.
What Gets Hoisted
- Variable declarations
- Function declarations
Variable Declarations
Example
Output: Undefined
In behind scene it looks like this because of Hoisting
means variable existed but not get their value.
Function Declarations
Functions are fully hoisted if you use function declaration. means if defined any function using function keyword then it will fully hoisted with their logic. not only declaration.
If we used to define function using arrow function then there declaration only hoisted not their logic and it will throw error.
Example with function keyword
Output: Hello
because it is fully hoisted with their declaration and logic.
Example with arrow function keyword
Output: This will give an error. Because only the variable name greet is hoisted not the function value.
So behind the scenes
Important Notes
vardeclarations are hoisted and initialized withundefinedletandconstdeclarations are hoisted but remain in the Temporal Dead Zone (TDZ) until the line where they are declared is executed- Function declarations are fully hoisted with their implementation
- Function expressions (arrow functions, function assigned to variables) are treated as variables and only the declaration is hoisted
- Always declare variables at the top of their scope to avoid confusion