
Gede Apriana
Fullstack & ML Developer
Loading...
Fullstack & ML Developer
Loading...
Date
April 02, 2025
Read Time
3 minutes
A deep dive into closures in JavaScript and how they help maintain state in functions.
What are JavaScript Closures?
A closure is a function that retains access to variables from its outer scope even after the outer function has executed.
Example:
A simple closure example in JavaScript:
Steps to Understand Closures:
• A function is defined inside another function.
• The inner function has access to variables from the outer function.
• The outer function executes, but its variables remain accessible to the inner function.
Example code:
JavaScript Code:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
};
}
const newFunction = outerFunction("Hello");
newFunction("World");
Closures are widely used in JavaScript for data encapsulation, event handling, and function currying.