Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
Declarations are Hoisted
var
Hoisted
The let and const Keywords
Variables and constants declared with let or const are not hoisted!
Initializations are Not Hoisted
JavaScript only hoists declarations, not initializations.
1 | var y; |
This is because only the declaration (var y
), not the initialization (=7
) is hoisted to the top.
Because of hoisting, y
has been declared before it is used, but because initializations are not hoisted, the value of y
is undefined.