Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
Understanding higher order functions in JS: how does the following code guarantee that the code will only be called once?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!