@jgCarroll/

counterFunction

JavaScript

A common interview question

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Answer uses a closure

function myFunc() {
  let count = 0
  return function() {
    count ++
    return count
  }
}

// 

const instanceOne = myFunc()
const instanceTwo = myFunc()
const instanceThree = myFunc()

console.log('instanceOne: ', instanceOne())
console.log('instanceOne: ', instanceOne())
console.log('instanceOne: ', instanceOne())
console.log('instanceOne: ', instanceOne())
console.log('instanceTwo: ', instanceTwo())
console.log('instanceTwo: ', instanceTwo())
console.log('instanceTwo: ', instanceTwo())
console.log('instanceThree: ', instanceThree())
console.log('instanceThree: ', instanceThree())
Native Browser JavaScript