Scope & Closures
Scope
- Global — everywhere
- Function — inside function
- Block — inside {} (let/const)
Closure
A function remembers variables from its outer scope even after that scope is gone.
A function remembers variables from its outer scope even after that scope is gone.
function makeCounter(){
let count=0; // private
return {
inc:()=>++count,
dec:()=>--count,
val:()=>count
};
}
const c=makeCounter();
c.inc(); c.inc();
console.log(c.val()); // 2
More in JavaScript