Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

260
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda