Hoisting in Action.
Here we can see that the variable is declared after it’s been used, so how does this still work?
How and Why?
Initializations are Not Hoisted.
Let and Const behave differently
You can see nothing is present in the results pane, that’s because these new keywords behave differently. The errors below are easy enough to understand, a const needs to be initialised when declared, whereas a let gets checked during the first cycle of the interpreter.
Put your declarations in scope.
What about Functions
Hoisting also applies to function declarations, which is why you can define your function after you call them! However, Function expressions/Anonymous methods do not get hoisted in a similar fashion to let and const. Take a look at this last CodePen, we can see that the variable declarations get hoisted from the bottom, but the anonymous function call does not, which kills the engine throwing errors.
Finally, it’s good to know that functions get hoisted before variables! So when refactoring legacy code, remember to look at the scope of all your variables and think about how the interpreter will be parsing the code you are modifying.