Stateful Functions

A common feature in other programming languages is usage of the static keyword to increase the lifetime (not scope) of a function variable to live beyond function invocations. Here is a C sample that achieves this:

  1. void called() {
  2. static count = 0;
  3. count++;
  4. printf("Called : %d", count);
  5. }
  6. int main () {
  7. called(); // Called : 1
  8. called(); // Called : 2
  9. return 0;
  10. }

Since JavaScript (or TypeScript) doesn’t have function statics you can achieve the same thing using various abstractions that wrap over a local variable e.g. using a class :

  1. const {called} = new class {
  2. count = 0;
  3. called = () => {
  4. this.count++;
  5. console.log(`Called : ${this.count}`);
  6. }
  7. };
  8. called(); // Called : 1
  9. called(); // Called : 2

C++ developers also try and achieve this using a pattern they call functor (a class that overrides the operator ()).