JavaScriptLesson 12 of 16
Closures
A JavaScript function remembers the variables of the place where it was created, even after the outer function has finished. That is a closure: a way to give a function a private memory.
Key points
- An inner function sees the outer function’s variables and keeps access to them
- Every call of the outer function creates a new, separate memory
- Code outside cannot reach those variables, which makes the data private
- A function factory: makeGreeter("Hello") returns a ready-made greeting function
- Counters, caches, once() and event handlers are all built on closures
Example
function createCounter() { let count = 0; return () => { count += 1; return count; };} const next = createCounter();console.log(next(), next(), next()); const other = createCounter();console.log(other()); const makeGreeter = (greeting) => (name) => `${greeting}, ${name}!`;const hello = makeGreeter("Hello");console.log(hello("Max"));next remembers its own count and raises it on every call. other was created separately, so it started at 1. makeGreeter returned a function that remembered the word Hello.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Finish the piggy bank: add(amount) adds to balance and returns the new balance, total() returns balance. Then write once(fn): it returns a function that runs fn only the first time. Output: Mia: 20, Leo: 3 and From outside: undefined.
Output
What your program prints appears here.