Scope and closures
Scope decides where a variable can be seen. Closures are what happens when a function remembers the variables around it, even after the outer code has finished. Closures power React hooks, event handlers, debouncing, and private data. They're one of the ideas that separate beginners from pros.
Block scope
let and const live only inside the nearest { ... } block.
Function scope and the scope chain
A function can see its own variables, then its parent's, then its grandparent's, all the way out to the global scope. This lookup path is called the scope chain.
Lookups only go outward: outer cannot see lesson.
Closures
When a function is created, it captures a reference to its surrounding variables. If you return that function, it keeps them alive.
makeCounter has finished running, yet count still exists, because the returned function closes over it. Nothing outside can touch count directly. That's data privacy.
Practical closure: function factories
Practical closure: memoization
Caching expensive results is a classic closure use:
The classic loop trap
Practice
Write createBankAccount(initial) that returns an object with deposit(amount), withdraw(amount) and getBalance(). The balance must be private (not a property on the object), and withdrawing more than the balance should return 'Insufficient funds'.
1.What is a closure?
2.Why does the var loop example print [3, 3, 3]?