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:
Closure interview questions to practice
Each one walks you through a real coding interview problem one hint at a time.
- JavaScript Scope » There's something tricky going on with scope in this JavaScript. Can you guess what will get logged to the console?
- What's Wrong with This JavaScript? » There's a tricky bug in this JavaScript. Can you find it?
Your first 3 questions are free. Just sign in, no credit card.
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!
Interview Cake