πŸš€ Frontend DSA 8 - πŸ”„ Currying in JavaScript: Define a Chainable Sum Function Without Final ()

JavaScript offers powerful flexibility when it comes to function chaining, currying, and type coercion. In this guide, we'll implement a function sum() that can be called repeatedly like this:

sum(0)(1)(2)(3)(4)(5)  ➞ 15

Notice: No final () required! 🀯


βœ… Problem Statement

Write a function such that:

console.log("" + sum(0)(1)(2)(3)(4)(5)); // 15

It should:

  • Allow infinite currying via sum(x)(y)...
  • Return the final result without an extra ()
  • Rely on implicit coercion using toString() or valueOf()

πŸ’» Final Working Code

function sum(x) {
  // Total will store the accumulating sum
  let total = x || 0;

  // Recursive function to chain more additions
  function next(y) {
    total += y || 0; // Add next value
    return next;     // Return itself for further chaining
  }

  // Override toString for final coercion when logged or used as string
  next.toString = function () {
    return total;
  };

  return next;
}

// πŸ” Test cases
console.log("" + sum(0)(1)(2)(3)(4)(5)); // 15
console.log("" + sum(5)(10)(-2));        // 13
console.log("" + sum(100));              // 100

Problem Statement


πŸ” How It Works

🧠 Key Concepts:

  1. Closure: total is preserved across chained calls.
  2. Function returning itself: next() returns next, enabling further chaining.
  3. Coercion with .toString(): JavaScript converts the function into a primitive value using toString() when used in a string context (like console.log("" + fn)).

⚠️ JavaScript Insight

If you used:

console.log(sum(1)(2)(3));  // ❌ Outputs [Function: next]

That’s because you're not coercing it to string/number.

βœ… Fix:

Use coercion explicitly:

console.log(+sum(1)(2)(3));    // 6
console.log("" + sum(5)(6));   // 11

You can also implement valueOf:

next.valueOf = () => total;

Then:

console.log(+sum(1)(2)(3)); // 6

πŸ§ͺ Additional Test Cases

console.log("" + sum());               // 0
console.log("" + sum(0)(0)(0));        // 0
console.log("" + sum(10)(20)(30));     // 60
console.log("" + sum(-5)(-10)(25));    // 10

⚑ Bonus: Arrow Function Version

const sum = x => {
  let total = x || 0;
  const next = y => (total += y || 0, next);
  next.toString = () => total;
  return next;
};

console.log("" + sum(1)(2)(3)); // 6

Code Block


πŸ’‘ When to Use This Pattern?

βœ… For:

  • Chainable APIs
  • Custom fluent interfaces
  • Logging or debugging DSLs

❌ Not for:

  • Production-critical arithmetic (due to coercion reliance)

Hey there from LearnYard! πŸ‘‹

Glad to see you exploring the free content from our course! We’ve shared 10 valuable articles at no cost to help you get a real feel of what’s inside.

If you’ve found these helpful, we’d love to know! πŸ’¬
Share your thoughts or key takeaways on LinkedIn, Twitter, or Instagram β€” and don’t forget to tag Gourav Hammad & Mohammad Fraz. We’ll personally respond to your post!

Thanks for being part of the LearnYard journey. Keep learning, keep growing! πŸš€


Loved the free content? Want access to the full course β€” for free? πŸ’Έ

Share the course with your friends using your affiliate link (you’ll find it on your profile or home page), and earn 20% commission on each sale.

Just 4–5 sales and you’ll recover the full course price of your course πŸ”
So why wait? Start sharing, start earning, and unlock the rest of the course effortlessly! πŸ› οΈπŸ“ˆ


πŸ“š Keywords for SEO

  • JavaScript Currying Without Final Call
  • Chainable Function Using toString in JavaScript
  • Implement sum(1)(2)... Without Final () in JavaScript
  • Currying and Overriding toString() in JavaScript
  • Function Chaining with Coercion in JavaScript
  • JavaScript Implicit Type Conversion in Functions
  • How to Use valueOf and toString for Currying
  • Override Coercion Methods in JavaScript Functions
  • JavaScript Lazy Evaluation with Coercion
  • Smart Function Chaining Techniques in JavaScript

πŸ“’ Hashtags for Visibility

#JavaScriptCurrying #ChainableFunctions #ToStringOverride #JavaScriptTips
#FunctionCoercionJS #LazyEvaluation #JSAdvancedConcepts #LearnJavaScript
#FrontendMasters #CodeNewbie #JSInterviewPrep #FunctionalProgrammingJS
#JSChainingWithoutCall #SmartJS #ValueOfToStringHack #JSClosures
#AdvancedJavaScript #JavaScriptDeepDive #TechLearning #FrontendDevelopment