| 41 | let name = "global scope"; |
| 42 | |
| 43 | function myFunc() { |
| 44 | // function/local scope |
| 45 | let name = "function/local scope"; |
| 46 | |
| 47 | if (true) { |
| 48 | // block scope |
| 49 | let name = "block scope 1"; |
| 50 | |
| 51 | for (let i = 0; i < 1; i++) { |
| 52 | // another block scope |
| 53 | let name = "block scope 2"; |
| 54 | console.log(name); // block scope 2 |
| 55 | // * if were not able to find the variable we need in the immediate scope, js will scope chain to the outer scopes to find one, in this case, if js did not find name in block scope 2, js will scope chain up and find the name in block scope 1 |
| 56 | // * we can go inward -> outward |
| 57 | // ! not outward -> inward |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // global declared variable |
| 62 | // ! don't do this |
| 63 | x = "bad"; |
| 64 | } |
| 65 | |
| 66 | myFunc(); |
| 67 | |