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

188
Vistas
What is the difference in these two closures?

I have recently learnt there is a few ways to create a closure (not just returning a function from a function), but also referencing the function as a callback in an event listener. This creates a closure too which explains why you can call an innerFunction using an eventListener even after an IIFE has finished executing and has not returned anything.

I like to think the main power of a closure is that not only does it find a variable in an outer function to use in an inner function, but it also updates its value so it can be stored. For example, you can push into an array and update it inside an outer function or update a score set as a primitive on an outer function.

However, if you can create a closure via referencing a function via an event Listener then why can you not update a local variable every time a function is called via an event listener, see below for what I am trying to get at.

function increaseScore(){
   var score = 0;
   score ++;
   console.log(score); // console.logs one everytime the event occurs
                       // despite the event listener creating a
                       // closure for this funciton
}
document.addEventListener("click", increaseScore);

function addScore(){
  var score = 0;

  return function (){ // This too is a closure created in a different way
                      // and increases every time the event is called
   score ++;
   console.log(score); // 1, 2, 3, 4, etc. every time the event occurs
  }
}
var keepScore = addScore();
document.addEventListener("click", keepScore);

Why is this the case? They are both examples of closures, one via an event Listener, another via returning a function, but only the function that returns a function gets updated from its original value of zero and is held in memory for every time the function is called and the first function resets to zero every time, and therefore is only ever printing 1 to the console. I can’t find an explanation anywhere.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The first is not a closure, since var score is declared within the function. Once you move that line outside of the function, it will work as expected (and the function will close over the global variable):

var score = 0;
function increaseScore(){
  score ++;
  console.log(score);
}
document.addEventListener("click", increaseScore);

Better examples of how to create closures without returning them might be

var keepScore;
function addScore(){
  var score = 0;

  keepScore = function (){ // this too is a closure
    score++;
    console.log(score);
  };
}
addScore();
document.addEventListener("click", keepScore);
function addScore(){
  var score = 0;

  function keepScore(){ // this too is a closure
    score++;
    console.log(score);
  };
  document.addEventListener("click", keepScore);
}
addScore();
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