Javascript Closures

JS Code Snippets Closures


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.


function counter() {
	//Local variable. Just like a private variable in an object.
  let count = 0;
  return function incCount() {
    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());

Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger