This topic is very very important in javaScript. It is an unknown behavior of javaScript. Shortly, javaScript compiler moves variables and function declarations
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
Variables and constants declared with let or const are not hoisted!
JavaScript Declarations are Hoisted
In JavaScript, a variable can be declared after it has been used.
In other words, a variable can be used before it has been declared.
Hoisting applies to variable declarations and to function declarations.
function declarations are hoisted before variable declarations.
Hoisting is only possible with declaration but not the initialization. JavaScript will not move variables that are declared and initialized in a single line.
I wrote a simple code in the following code then same code is changed a little bit. number variable is declared after used in second example.
RunKit
RunKit notebooks are interactive javascript playgrounds connected to a complete node environment right in your browser. Every npm module pre-installed.
As you can see in the following code, number is undefined. Because it is initialized when it is declared. So, it is not hoisted.
RunKit
RunKit notebooks are interactive javascript playgrounds connected to a complete node environment right in your browser. Every npm module pre-installed.
RunKit
RunKit notebooks are interactive javascript playgrounds connected to a complete node environment right in your browser. Every npm module pre-installed.
Hoisting of function
JavaScript compiler moves the function definition at the top in the same way as variable declaration. That means, function hoisting only works with function declaration and not with function expression.
RunKit
RunKit notebooks are interactive javascript playgrounds connected to a complete node environment right in your browser. Every npm module pre-installed.
JavaScript compiler does not move function expression.
RunKit
RunKit notebooks are interactive javascript playgrounds connected to a complete node environment right in your browser. Every npm module pre-installed.
As shown in the following example, square function is failing in line 2 because of function expression.
RunKitDeclare Your Variables At the Top !
JavaScript compiler moves variables and function declaration to the top and this is called hoisting.
Only variable declarations move to the top, not the initialization.
Functions definition moves first before variables.
To avoid bugs, always declare all variables at the beginning of every scope.
JavaScript in strict mode does not allow variables to be used if they are not declared.
Order of precedence
Function declarations are hoisted over variable declarations but not over variable assignments.
- Variable assignment takes precedence over function declaration.
- Function declarations take precedence over variable declarations.