Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda