Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!