Scope, Closures, and this
Lexical scope decides which variables a function can see. A closure remembers variables from its outer scope. this depends on how a function is called (except arrows).
- Inner functions can read outer lets/consts.
- Closures power private state and callbacks.
- Prefer arrows for callbacks when you want lexical this.
function makeCounter() {
let n = 0;
return () => {
n += 1;
return n;
};
}
const c = makeCounter();
console.log(c(), c());
After you read this chapter, use Write (when available) and Quiz on this page to lock it in.