A Counter the Functional Way

Photo by Steve Johnson on Unsplash

There are many ways to create a counter; one way is the object-oriented programming way:

  • First, create a class Counter.
  • Create an object counter.
  • Now, Every time you call the counter object, it gets incremented by 1.

Now, the functional programming way:

  • First, we create a function Counter.
  • Assign the function to a variable counter (a high order function).
  • Then every time you call the counter, it gets incremented by 1.
free variable: count
cell content: 4

This technique is known as a closure:

  1. It is a function (Counter) with a nested function (increment).
  2. The function returns a nested function.
  3. The nested function has access to a variable not in its scope (count, a free variable).

So what makes closure special?
Well, it is simply a function capable of storing data. This approach is much cleaner than storing values in global variables.

Bonus: (similar code in Lua):