Variables and constants declared with let or const are not hoisted!
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.
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.
As you can see in the following code, number is undefined. Because it is initialized when it is declared. So, it is not hoisted.
Hoisting of function
As shown in the following example, square function is failing in line 2 because of function expression.RunKit
Declare Your Variables At the Top !
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.
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.