Understand closures and scope: 15 levels of var vs let, hoisting and lexical scope. The most brain-bending JavaScript scope game for developers.
let and const have block scope: a variable only exists inside the {} where it is declared. var has function scope, so it ignores {} blocks.
Hoisting: JavaScript "lifts" a var declaration to the top of its scope. Only the declaration, not its assignment. So var x exists but holds undefined before the assignment line.
let and const have a Temporal Dead Zone (TDZ): the stretch from the start of the block to the declaration line, where the variable exists but cannot be used yet. Reaching it gives a ReferenceError.
A closure: a function that "remembers" the variables of the scope it was made in. Even after the outer function has finished, the inner function can still reach its variables.
A classic trap: var in a loop does not make a new scope for each turn. Every closure uses ONE and the same variable i. By the time they are called, i is already 3 (the loop’s final value). The fix: use let.
IIFE: (function() { ... })() is a function that is called at once. It is useful for making a private scope: the variables inside it do not leak out.
x tonight: one in the yard, one in the if booth. From each point, who answers, and with what value?y is declared with var, twice. From each point, who answers, and with what value?greet has a house of its own. From inside its house and from the yard, who answers?setNama has been called and has finished. Who can still be reached from the yard?x is only filled in on the second line. What is heard from x before and after that line?y is declared with let inside the try. What happens when y is asked for before its line?sapa is called on the first line, before its declaration. Which functions and variables can already be reached?buatPesan returns a function that is kept in halo. Who answers, and what does that function still remember?hitung is called three times. Who answers, where is angka kept, and what does it hold?var i. Who do they hear, and what is i when they are called?let i: let makes a new scope on every turn. Which i does each function remember?dalam stands inside luar. The scope chain decides who answers from each point.And more, 15 levels in all.