How do you implement sum(1)(2)(3)(4)..(n) in JavaScript?
function sum(a) { return function(b) { if (b !== undefined) return sum(a + b); return a; }; }. Each call returns a function that accumulates. Call with no argument to get the result: sum(1)(2)(3)().
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Implement sum(1)(2)(3)(4)..(n) in JavaScript
Two approaches: (1) call with no argument: sum(1)(2)(3)() - check if b !== undefined. (2) toString override: sum(1)(2)(3) + 0 - JavaScript calls toString when arithmetic is performed.
Currying and closures. Each call returns a function that closes over the accumulated sum. Without closures, the inner function would not have access to the previous arguments.
function sum(n) { const fn = m => sum(n + m); fn.toString = () => n; return fn; }. When JavaScript needs a primitive (like + 0 or console.log), it calls toString and returns the accumulated sum.
Still have questions?
Browse all our FAQs or reach out to our support team
