Closure in JavaScript (Live Playground)
In this tutorial, we will dive deeper into closures, an essential concept in JavaScript. Closures allow you to access variables from an outer function even after the outer function has completed its execution. This can be useful for creating private variables and controlling access to data.
What are Closures?
A closure is a function that retains access to its outer (enclosing) function's variables, even after the outer function has completed its execution. In other words, closures allow inner functions to remember the environment in which they were created.
function outerFunction() {
let outerVar = 'I am from the outer function.';
function innerFunction() {
console.log(outerVar);
}
return innerFunction;
}
const innerFunc = outerFunction();
innerFunc(); // Output: I am from the outer function.
Practical Use of Closures
Closures can be used to create private variables, implement encapsulation, and create function factories.
Private Variables
In JavaScript, you can use closures to create private variables that can't be accessed directly from outside the function.
function createCounter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const counter = createCounter();
counter(); // Output: 1
counter(); // Output: 2
Encapsulation
Closures can also help you implement encapsulation, which is the practice of bundling related data and methods within an object and controlling access to them.
function createPerson(name, age) {
return {
getName: function () {
return name;
},
getAge: function () {
return age;
},
setAge: function (newAge) {
age = newAge;
},
};
}
const person = createPerson('John', 25);
console.log(person.getName()); // Output: John
console.log(person.getAge()); // Output: 25
Function Factories
Function factories are functions that return other functions with specific behavior. Closures can help you create function factories by remembering the environment in which they were created.
function createMultiplier(multiplier) {
return function (number) {
return number * multiplier;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // Output: 10
console.log(triple(5)); // Output: 15
Conclusion
Closures are an essential concept in JavaScript, allowing inner functions to retain access to their enclosing function's variables even after the outer function has completed. By understanding closures, you can write more efficient and maintainable code, create private variables, implement encapsulation, and create function factories.