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?
Hoisting will move all declarations to the top of the current scope (top of the current file or function).
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.
The main reason for this is because let and const are block scoped. var on the other hand is not and therefore can be hoisted up to the global context (as long as 'use strict' is not present
James - https://dev.to/jamesthomson