Surya JS Journey
Learn JavaScript through concepts, code, and guided practice.
A focused workspace for concept study, interactive examples, visual explanations, and challenge solving.
Closure
Closures let inner functions keep access to variables from the scope where they were created.
A closure is created when a function remembers variables from its lexical scope even after the outer function has finished running. This is one of the most important ideas in JavaScript because it powers patterns like private state, factory functions, and callbacks that need access to surrounding data.
Explanation
A closure is created when a function remembers variables from its lexical scope even after the outer function has finished running. This is one of the most important ideas in JavaScript because it powers patterns like private state, factory functions, and callbacks that need access to surrounding data.
Key Points
- Closures depend on lexical scope, not where a function is called from.
- They allow functions to preserve state between calls.
- They are commonly used for encapsulation and factories.
Common Mistakes
- Assuming the outer variables are copied instead of referenced.
- Forgetting that closures can retain memory if they keep large objects alive.
- Using closures in loops without understanding how the captured variable behaves.
Practice Workspace
closure.js
Edit the code, run it in the browser, and inspect the console output below. Reset restores the original snippet for this page.
Editor
12 lines
Output
0 entries
Mode
practice
Workspace Notes
Changes stay local until you run the code. Reset restores the original snippet immediately for another pass.
Editor Actions
Use the editor to explore the example, then run it to inspect the console.
Run the code to see output here.
Expected Output
1
2Continue in Playground
Open this concept example in the shared playground to keep experimenting without leaving the broader workspace flow.
Open in PlaygroundRelated Concepts