MARCUS ÖSTERBERG

JavaScript Closures

JavaScript Closures

Closures are awesome and confusing

I want to share how I started to understand Closures in JavaScript. This is a beginner friendly view with a simple example. Closures is a function wrapped inside of a functions body that can be referenced to its scope chain e.g. outer variables.

Definition from the book Speaking JavaScript “A closure is a function plus the connection to the scope in which the function was created” -Dr.Axel Rauschmayer

So this is how it could look like

function newCounter() {
  var counter = 0;
   return function increment() {
    counter += 1;
   }
}

var counter1 = newCounter();
var counter2 = newCounter();

counter1(); // Number of events: 1
counter1(); // Number of events: 2
counter2(); // Number of events: 1
counter1(); // Number of events: 3


newCounter closes over increment, counter can be referenced to and accessed by increment. The Closure now holds the scope chain and prevents it from being garbage collected.

counter1 and counter2 will keep track of their own value.

This is a very simple but hopefully a clear perspective of what closures are.
There is some really good explanations out there on why closures could be used, If you have some good knowledge or resources please share below.

Enjoy your code.


comments powered by Disqus
Archive