Javascript - Closures
Code Life
By Pierre Marsaa
Closures: A Function That Remembers
Look closely at the code below: makeGreeter(name) creates an inner function greet and returns that inner function.
Normally, local variables disappear as soon as a function finishes. Yet even after makeGreeter("Zap") has finished running, calling the returned greetZap() function still remembers that name is "Zap":
↗️
Loading editor...
↶
↷
How is that possible? Whenever an inner function is created, it packs a ”backpack” containing the variables from its surrounding scope (name). Even after the outer function finishes, the inner function keeps that backpack with it.
A function together with the outer variables it remembers is called a closure!
Verify