0

I am trying to understand functional programming and saw the following example:

function onceOnly(f) {
    var hasRun = false;
    return function() {
        if(!hasRun){
            hasRun = true;
            return f();
        }
    }
}

// Call as many times as you like
var sendWelcomeEmail = onlyOnce(function() {
    emailServer.send(...);
});

There are a few things that I do not understand about this.

  • This technique should guarantee that emailServer.send(...) will be called only once. How does it do so? How does the state of hasRun get saved?
  • Is there any use to creating a function which returns f() inside onceOnly(f)? Why did we not simply do the following:
function onceOnly(f) {
    var hasRun = false;
    if(!hasRun){
        hasRun = true;
        return f();
    }
}

The source of this code can be found here

Thank you.

speakernode
  • 25
  • 1
  • 6
  • 2
    You can see this answer for information about how the state of `hasRun` is "saved": [How do JavaScript closures work?](https://stackoverflow.com/a/111111) – Nick Parsons Oct 10 '21 at 03:50

1 Answers1

1

The aim of onlyOnce is to return a function, not calling a function. Your second example is calling the function and return the result of f.

Wherease, with the first implementation

//return a reference to an anonymous function
var sendWelcomeEmail = onlyOnce(...);
//you can use it to call after
sendWelcomeEmail();

Simply put a console.log() just before return f() you'll see the difference.

hasRun is first initiate with false. Once sendWelcomeEmail() is called, hasRun will be set to true. Since sendWelcomeEmail is referenced to an anonymous function, it is unique and exist in the memory, a second call to this same function will not trigger f() because hasRun is also uniquely referenced and got memorized.

Thanh Trung
  • 3,566
  • 3
  • 31
  • 42
  • I see, so it is because `sendWelcomeEmail` holds a reference to `hasRun` in the memory, if I understood this correctly? Which would mean that `hasRun` will get saved once it is changed. – speakernode Oct 10 '21 at 04:23
  • 1
    Yes, as long as the anonymous function still exist. `hasRun` is still used and get referenced in memory – Thanh Trung Oct 10 '21 at 04:32