What is Closure in JavaScript: Simple Explanation and Example
closure in JavaScript is a function that remembers and can access variables from its outer (enclosing) function even after that outer function has finished running. It allows the inner function to keep using those variables, creating a private space for data.How It Works
Imagine you have a box inside another box. The inner box can see and use things inside the outer box, even if the outer box is closed. In JavaScript, when a function is created inside another function, the inner function keeps a reference to the variables of the outer function. This means the inner function can still use those variables later, even after the outer function has finished.
This happens because JavaScript keeps the environment (variables and their values) alive for the inner function. This is useful because it lets you create functions that remember information, like a secret note that only the inner function can read.
Example
This example shows a function that creates a counter. Each time you call the inner function, it remembers the count and adds one.
function createCounter() { let count = 0; return function() { count += 1; return count; }; } const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 console.log(counter()); // 3
When to Use
Closures are useful when you want to keep some data private and safe from outside changes. For example, you can use closures to create counters, manage settings, or handle events where you need to remember information between calls. They help organize code by keeping related data and functions together.
In real life, think of a closure like a backpack that carries your tools (variables) wherever you go (inside the inner function), so you always have what you need.
Key Points
- A closure is a function that remembers variables from its outer function.
- It allows data to be private and persistent between function calls.
- Closures help write cleaner and more modular code.
- They are commonly used for data hiding and creating function factories.