JSFiddle - React, Tailwind, and code Playground
JavaScript
// Source: https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8
function createCounter() {
let counter = 0
const myFunction = function() {
counter = counter + 1
return counter
}
return myFunction
}
const increment = createCounter()
// For each of these, resetting the counter to 0 (line 4) 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)
// Excerpt from the source link, above:
// The closure is a collection of all the variables in scope at the time of
// creation of the function.