Facebook Pixel

How do you implement sum with toString in JavaScript?

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.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in 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)().

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.

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.