About
In this code snippet, we’ll learn about closures in Javascript.
A closure is simply a function within a function. With this, we can achieve variable encapsulation. In other OOP languages, this would be done by making a private property inside a class. This way the variables inside are isolated and protected from the global space.
Let’s see the code example below.
Code:
function counter() {
//Local variable. Just like a private variable in an object.
let count = 0;
return function incCount() {
count++;
return count;
};
}
//More counters can be made and each one will have it's own internal variables that are protected form the global space.
const counter1 = counter();
const counter2 = counter();
console.log("Counter1: " + counter1());
console.log("Counter1: " + counter1());
console.log("Counter2: " + counter2());
console.log("Counter1: " + counter1());
console.log("Counter2: " + counter2());





