Closures (in JavaScript)

If you return a function (instead of a value or object), you will have to think about closures. You are not just returning the function definition but also the all the variables in scope at the time of creation of the function! This is called a closure. A read a nice Medium article with some very detailed step-to-step explanation, I’d like to recommend.

The best example is following:

1: function createCounter() {
 2:   let counter = 0
 3:   const myFunction = function() {
 4:     counter = counter + 1
 5:     return counter
 6:   }
 7:   return myFunction
 8: }
 9: const increment = createCounter()
10: const c1 = increment()
11: const c2 = increment()
12: const c3 = increment()
13: console.log('example increment', c1, c2, c3)

The output is ‘example increment’, 1, 2, 3 – the variable “counter” (l2) is inside the closure of “increment (l9). And therefore the output is not 1, 1, 1.

A little bit more interesting os folliwing example, I’d like to add

function createCounter() {
   let counter = 0
   const myFunction = function() {
     counter = counter + 1
     return counter
   }
   return myFunction
}
const increment = createCounter()
const c1 = increment()
const c2 = increment()
const c3 = increment()
console.log('example increment', c1, c2, c3)
const increment2 = createCounter()
console.log('example increment', increment2(), increment2(), increment2())

What is the about here?

Well, the answer is: both times ‘example increment’, 1, 2, 3. increment2 has its own closure!