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

143
Vistas
Return a function that when invoked increments and returns a counter variable

Need help, I'm stuck! I'm given

function counter(){}

and I read up on some materials and managed to come up with this

function counter(){
var currentValue = 0;

var increment = function(val){

currentValue += val;
console.log(currentValue);
}

its not working and I don't really 100% understand closures yet. Would like to know what is needed in the code and how it worked. Thank you!

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

0

The basic idea is that you create an inner function that captures the local variable and then return that function to the caller, who will call it:

function counter(){
  var currentValue = 0;

  return function(val){
    currentValue += val;
    return currentValue;
  }  
}

// create a counter and increment by one
let c = counter()
console.log(c(1))
console.log(c(1))
console.log(c(1))

// create a new counter and increment it by 2
let e = counter()
console.log(e(2))
console.log(e(2))
console.log(e(2))

about 4 years ago · Juan Pablo Isaza Denunciar

0

it looks like every time you run the function, you are updating the currentValue variable to 0. A simple solve would be to define the currentValue variable as a global variable like this:

var currentValue = 0;
function counter(val) {   //where val is a number and the number you want your counter to change by
    currentValue += val;
console.log(currentValue);
}
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Maybe this code is needed

function counter(){
  var currentValue = 0;

  return function(val){
    currentValue += val;
    return currentValue;
  }
}

var c = counter();
console.log(c(10));
console.log(c(20));
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