This content originally appeared on DEV Community and was authored by Md Readwan
Closures are a powerful feature in JavaScript that allow functions to retain access to their lexical scope, even when the function is executed outside that scope. This can sound abstract, but with some simple examples, you’ll see how closures can be both intuitive and incredibly useful in real-world applications.
What is a Closure?
A closure is created when a function is defined within another function, and the inner function retains access to the outer function’s variables. Essentially, a closure gives you access to an outer function’s scope from an inner function.
Here’s a simple definition:
- Closure: A combination of a function and its lexical environment within which that function was declared.
Basic Example
Let’s start with a basic example to illustrate the concept of closures:
function outerFunction() {
let outerVariable = 'I am from the outer function';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const myClosure = outerFunction();
myClosure(); // Outputs: I am from the outer function
In this example:
-
outerFunctioncontains a variableouterVariableand an inner functioninnerFunction. -
innerFunctionaccessesouterVariableand logs it to the console. -
outerFunctionreturnsinnerFunction, and we store it inmyClosure. - When
myClosureis called, it still has access toouterVariableeven thoughouterFunctionhas finished executing. This is a closure in action.
Real-World Example: Creating Private Variables
Closures are often used to create private variables in JavaScript. Here’s an example of how you can use closures to encapsulate data and provide a controlled interface to interact with it:
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
console.log(count);
},
decrement: function() {
count--;
console.log(count);
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
counter.increment(); // Outputs: 1
counter.increment(); // Outputs: 2
counter.decrement(); // Outputs: 1
console.log(counter.getCount()); // Outputs: 1
In this example:
-
createCounterfunction defines a variablecountand returns an object with three methods:increment,decrement, andgetCount. - The methods
incrementanddecrementmodifycount, whilegetCountreturns its current value. - The
countvariable is private tocreateCounterand cannot be accessed directly from outside. This encapsulation is made possible by closures.
Real-World Example: Delayed Execution
Closures are also useful for functions that need to remember the context in which they were created, such as setting up delayed execution with setTimeout:
function greet(name) {
return function() {
console.log('Hello, ' + name);
};
}
const delayedGreeting = greet('Alice');
setTimeout(delayedGreeting, 2000); // Outputs: Hello, Alice after 2 seconds
In this example:
-
greetfunction returns another function that logs a greeting message. -
delayedGreetingstores the returned function with the capturednamevariable. -
setTimeoutexecutesdelayedGreetingafter 2 seconds, and it still has access toname(Alice) due to the closure.
Conclusion
Closures are a fundamental concept in JavaScript that allow functions to access their lexical scope even after the outer function has finished executing. They enable powerful patterns such as data encapsulation, private variables, and delayed execution.
And Finally,
Please don’t hesitate to point out any mistakes in my writing and any errors in my logic.
I’m appreciative that you read my piece.
This content originally appeared on DEV Community and was authored by Md Readwan