@thebarefootdev
All things Software Dev & Architecture

Follow

All things Software Dev & Architecture

Follow

JavaScript closure illustrated in one example

Demystifying the closure in one go!.

@thebarefootdev's photo
@thebarefootdev
·Jun 7, 2021·

1 min read

function countFactory(isIncrement, start){
  return function(){
    return isIncrement 
      ? start += 1
      : start -= 1
  }
}

const incByOne = countFactory(true, 0)

const i1 = incByOne()
const i2 = incByOne()
const i3 = incByOne()

const decByOne = countFactory(false, 4)

const d1 = decByOne()
const d2 = decByOne()
const d3 = decByOne()

console.log(i1,i2,i3) // 1 2 3
console.log(d1,d2,d3) // 3 2 1

Spot the closure? Think of it as an (en)closure, wrapping up our start value upon function assignment

 
Share this