By the end of this lesson, you will understand how closures work in JavaScript and be able to create a simple counter function using them.
Closures are a feature in JavaScript that allows a function to remember variables from its parent scope, even when that function is executed outside that scope. For example, think of a restaurant where the chef can remember the special recipe for a dish. Even if the chef leaves the kitchen, he can still cook it because he remembers the ingredients.
File: counter.js
function createCounter() {
let count = 0; // This variable is private to the closure
return { // Return an object with methods
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // Output: 1
console.log(counter.increment()); // Output: 2
console.log(counter.decrement()); // Output: 1
console.log(counter.getCount()); // Output: 1
1
2
1
1
In this code:
Create a counter function that can reset the count value to zero. Use closures to ensure the count variable remains private.
function createResettableCounter() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
reset: function() {
count = 0;
return count;
},
getCount: function() {
return count;
}
};
}
const resettableCounter = createResettableCounter();
console.log(resettableCounter.increment()); // Output: 1
console.log(resettableCounter.reset()); // Output: 0
console.log(resettableCounter.getCount()); // Output: 0