
Learn Javascript Closure with 10 examples
A closure in JavaScript is a function that remembers the environment in which it was created. This means that the function has access to variables from its outer scope, even after the outer function has finished executing.
Here’s a detailed explanation along with 10 different examples:
Explanation
A closure is created when a function is defined inside another function, allowing the inner function to access variables and parameters of the outer function. This is due to JavaScript’s lexical scoping, where the scope of a variable is determined by its position in the source code.
Examples
1. Basic Closure
function outerFunction() {
let outerVariable = 'I am outside!';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const closure = outerFunction();
closure(); // Output: I am outside!
2. Closure with Parameters
function createGreeting(greeting) {
return function(name) {
console.log(greeting + ', ' + name);
}
}
const sayHello = createGreeting('Hello');
sayHello('Alice'); // Output: Hello, Alice
3. Private Variables
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
}
}
}
const counter = createCounter();
console.log(counter.increment()); // Output: 1
console.log(counter.increment()); // Output: 2
console.log(counter.decrement()); // Output: 1
4. Factory Functions
function createMultiplier(multiplier) {
return function(value) {
return value * multiplier;
}
}
const double = createMultiplier(2);
console.log(double(5)); // Output: 10
const triple = createMultiplier(3);
console.log(triple(5)); // Output: 15
5. Function Factories
function makeFunctionArray() {
const arr = [];
for (let i = 0; i < 5; i++) {
arr.push(function() { console.log(i); });
}
return arr;
}
const functionArr = makeFunctionArray();
functionArr[0](); // Output: 0
functionArr[1](); // Output: 1
6. Maintaining State
function createToggle(initialState) {
let state = initialState;
return function() {
state = !state;
return state;
}
}
const toggle = createToggle(true);
console.log(toggle()); // Output: false
console.log(toggle()); // Output: true
7. Callback Functions
function fetchData(callback) {
let data = 'Some data';
callback(data);
}
function logData(data) {
console.log('Received:', data);
}
fetchData(logData); // Output: Received: Some data
8. Setting Timeouts
function createDelayedLogger(message, delay) {
return function() {
setTimeout(function() {
console.log(message);
}, delay);
}
}
const logHello = createDelayedLogger('Hello, world!', 1000);
logHello(); // Logs "Hello, world!" after 1 second
9. Module Pattern
const counterModule = (function() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
getCount: function() {
return count;
}
}
})();
console.log(counterModule.increment()); // Output: 1
console.log(counterModule.getCount()); // Output: 1
10. Event Handlers
function attachClickHandler() {
let clickCount = 0;
document.getElementById('myButton').addEventListener('click', function() {
clickCount++;
console.log('Button clicked', clickCount, 'times');
});
}
attachClickHandler();
These examples demonstrate various ways closures can be utilized in JavaScript, highlighting their power in managing state, creating factory functions, maintaining private variables, and more.