Skip to main content

Recursion / Function

๐Ÿš€ 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