A closure is a method that accesses a variable "outside" itself. For example:
We'd say that message is "closed over" by sayMessage.
One useful thing to do with a closure is to create something like an "instance variable" that can change over time and can affect the behavior of a method.
Why did we put nextGeneratedId in an immediately-executed anonymous method? It makes nextGeneratedId private, which prevents accidental changes from the outside world:
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!