Monday, July 15, 2019

JavaScript Closure Summary

Excellent article explaining closures: JS Closure Article
The fiddle: https://jsfiddle.net/h59k1v8z/

The important point:
The closure is the function AND a collection of all the variables in scope at the time of creation of the function.

In this example, the closure is in bold.

function createCounter() {
  let counter = 0 // the counter variable is included in the closure, but the initialization to 0 is not
  const myFunction = function() {
   counter = counter + 1
   return counter
  }
  return myFunction
}

const increment = createCounter()

// For each of these, resetting the counter to 0 (first line in createCounter()) doesn't get hit,
// BUT since counter was in scope at the time myFunction was created, it's included in the
// closure. So counter is available, and the output, below, is indeed "example increment 1 2 3".
const c1 = increment()
const c2 = increment()
const c3 = increment()

console.log('example increment', c1, c2, c3)