Clousers

Narendra

Narendra / May 01, 2023

1 min read––– views

What are they? In JavaScript, a closure is created when a function is defined within another function, and the inner function retains access to the variables and parameters of the outer function, even after the outer function has completed its execution.

Why closures?

  • Can be used to create private methods and variables - data-hiding & encapsulation.
  • Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods.
var makeCounter = function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },

    decrement: function() {
      changeBy(-1);
    },

    value: function() {
      return privateCounter;
    }
  }
};

var counter1 = makeCounter();
var counter2 = makeCounter();

alert(counter1.value());  // 0.

counter1.increment();
counter1.increment();
alert(counter1.value()); // 2.

counter1.decrement();
alert(counter1.value()); // 1.
alert(counter2.value()); // 0.

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles.

- subscribers – View all issues