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

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

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