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

117
Vistas
JavaScript Closures calculate sum

I just started learning closures in JavaScript and I'm trying to understand a basic problem.

For example, I'm trying to implement the sum method: sum(1)(4)(5)

const sum = (a) => {
    return (b) => {
        if(typeof b === 'number')
            return sum(a+b)
        return a;
    }
}

When I call: console.log(sum(1)(4)(5)()) it works perfect and return 10. However, if I call console.log(sum(1)(4)(5)), it returns [Function (anonymous)]. Why?

Thanks

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

0

Every time you call your function like:

sum(1)(10)

you are returning the inner function:

(b) => {
        if(typeof b === 'number')
            return sum(a+b)
        return a;
    }

Because type of b === 'number' and you are returning sum(a+b) that calls again the function sum and returns again the inner function. Thats why when you finally put the last parenthesis like:

sum(1)(10)()

The inner function will execute and type of b in this case is different from number and will return 'a' that already contains the sum of the values.

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