Facebook Pixel

What is the time complexity of sum(1)(2)(3)..(n)?

O(n) where n is the number of chained calls. Each call creates a new function and closure. The space complexity is also O(n) due to the call stack (unless tail-call optimization is available, which it is not in most JS engines).

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How the sum(1)(2)(3) Function Uses Closures

Each call to sum(a) returns a function that closes over a. When called with b, it returns sum(a + b), creating a new closure with the accumulated total. The closure keeps the running sum alive between calls.

Yes. Each sum(a) call creates a new function with a new closure over a. The previous closure is replaced, but the accumulated value (a + b) is passed forward to the new sum call.

b is undefined. The function checks if (b !== undefined), which is false. It returns a (the accumulated sum). This is how the chain terminates and the result is retrieved.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.