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

145
Visualizações
How to reuse a closure function assigning it to a variable or constant in JavaScript

I'm solving an exercise that is intended to use closures. You must create a function that returns a function that will store a value and, when you reuse it, add the new value to the saved one.

const firstValue = myFunction(3);
const secondValue = firstValue(4);
// result => 7

this is the code that I'm using to practice closures:

function addNumbers(num) {
    let storage = 0
    let n = num
    function adding(n) {
        storage += n;
        return storage
    }
    return adding(n)
}

let firstAttemp = addNumbers(4)
let secondAttemp = firstAttemp(3)

console.log(firstAttemp)

this throw an error "Uncaught TypeError: firstAttemp is not a function"

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

const addNumbers = (a) => (b) => a + b

It's called currying, more details here.

P.S. If you want to use function syntax, it will look like this:

function addNumbers(a) {
  return function (b) {
    return a + b
  }
}
about 4 years ago · Santiago Gelvez Relatório

0

As @skara stated in their comment, return adding(n) returns the result of calling adding instead of returning the function so that it may be called later with firstAttemp(3).

Unfortunately though it still doesn't work because you don't actually assign the value passed to addNumber to be added later.

function addNumbers(num) {
  let storage = 0;
  let n = num;

  function adding(n) {
    storage += n;
    return storage;
  }
  return adding;
}

let firstAttemp = addNumbers(4);
let secondAttemp = firstAttemp(3);

console.log(firstAttemp);
console.log(secondAttemp); // 3! 😢

You don't actually need to manually save the value of num to a variable as it is captured in the closure arround adding that is being returned.

function addNumbers(num) {
  function adding(n) {
    return num + n;
    return storage;
  }
  return adding;
}

let firstAttemp = addNumbers(4);
let secondAttemp = firstAttemp(3);

console.log(secondAttemp); // 7 👍🏻

about 4 years ago · Santiago Gelvez 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