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

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

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 Denunciar

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 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