JavaScript Function Closures
A closure in JavaScript is a function that has access to its outer (enclosing) function's variables, even after the outer function has executed. Closures allow functions to retain their scope and are widely used in JavaScript for data privacy and function factories.
Key Topics
Closure Basics
A closure is created whenever a function is defined inside another function and accesses variables from its outer function's scope.
function outerFunction() {
let outerVariable = "I'm from outer scope";
return function innerFunction() {
console.log(outerVariable);
};
}
const closureFunction = outerFunction();
closureFunction();
Output
> I'm from outer scope
Explanation: The innerFunction
forms a closure over outerFunction
, allowing it to access outerVariable
even after outerFunction
has finished executing.
Data Privacy
Closures can be used to create private variables, ensuring encapsulation and data protection in JavaScript.
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
console.log(count);
},
decrement: function() {
count--;
console.log(count);
}
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1
Output
> 1
> 2
> 1
Explanation: The count
variable is private to createCounter
, and its value can only be modified using the increment
and decrement
methods.
Function Factories
Closures are often used to create function factories that generate functions customized with preset variables.
function createMultiplier(multiplier) {
return function(number) {
return number * multiplier;
};
}
const double = createMultiplier(2);
console.log(double(5)); // 10
console.log(double(10)); // 20
Output
> 10
> 20
Explanation: The createMultiplier
function generates new functions with a specific multiplier value, demonstrating closures in action.
JavaScript Usage in DOM
Below is a complete DOM example demonstrating closures to maintain state in a dynamic web application.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Function Closures in DOM</title>
</head>
<body>
<button id="increment">Increment</button>
<button id="decrement">Decrement</button>
<p id="counter">0</p>
<script>
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
document.getElementById("counter").textContent = count;
},
decrement: function() {
count--;
document.getElementById("counter").textContent = count;
}
};
}
const counter = createCounter();
document.getElementById("increment").addEventListener("click", counter.increment);
document.getElementById("decrement").addEventListener("click", counter.decrement);
</script>
</body>
</html>
Key Takeaways
- Closures: Functions retain access to variables in their outer scope.
- Data Privacy: Use closures to create private variables and methods.
- Function Factories: Generate customized functions using closures.
- DOM Integration: Use closures to manage state dynamically in web applications.