## Notes `Hoisting` means to move something to the top of `lexical scope`. ```javascript console.log(myVariable); // undefined var myVariable = 1; console.log(myVariable); // 1 ``` In this case, the variable *declaration* is accessible at the top of the file. However its initialized value is not yet accessible. ## Using Let and Const ```javascript console.log(myVariable); // ReferenceError: Cannot access 'myVariable' before initialization. const myVariable = 2; ``` Using `let` and `const` addresses the iniquity of initialization that happens with `var`. These variables are still hoisted because JavaScript still knows about them. However they are hoisted without the *default initialization*. ## Scope `var` outside of a function is available to the whole `window` in the browser. This can lead to debugging errors if multiple places modify the value. ```javascript // valid var myVariable = 1; var myVariable = 2; myVariable = 3; ``` `let` is block-scoped, so the following is fine though ```javascript let myVariable = "hi"; if (true) { let myVariable = "hello"; console.log(myVariable); // hello } console.log(myVariable); // hi ``` `const` is also block-scoped. ## References - [[JavaScript Study MOC]] - [JavaScript Let Const Hoisting - FreeCodeCamp](https://www.freecodecamp.org/news/javascript-let-and-const-hoisting/)