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.
How does the sum(1)(2)(3) function know when to stop?
More FAQs in Currying Interview Questions in JavaScript
function sum(a) { return function(b) { if (b !== undefined) return sum(a + b); return a; }; }. Call with no argument to terminate and return the accumulated sum.
Same pattern: function sum(a) { return function(b) { if (b !== undefined) return sum(a + b); return a; }; }. Or use toString: function sum(n) { const fn = m => sum(n + m); fn.toString = () => n; return fn; }.
function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn(...args); return (...next) => curried(...args, ...next); }; }.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.