Skip to main content

Recursion / Function

๐Ÿš€ Frontend DSA 7 - ๐Ÿงฎ Currying in JavaScript: Create a Sum Function with Infinite Calls Ending with ()

Currying is a powerful and elegant technique in JavaScript used to transform functions with multiple arguments into a sequence of functions, each taking a single argument.

In this guide, weโ€™ll build a recursive curried sum function that allows you to call:

sum(1)(2)(3)(4)(5)(); // โžž 15

Letโ€™s understand how this magic works. ๐Ÿง™โ€โ™‚๏ธโœจ


โœ… Goal

We want to define a function sum() such that:

sum(0)(1)(2)(3)(4)(5)(); // โœ… Output: 15

It should support:

  • Chainable calls: sum(1)(2)(3)...
  • Termination with an empty () call
  • Recursive addition of all arguments

๐Ÿง  JavaScript Currying Function โ€“ Final Code

function sum(x) {
  // Define a nested function that continues the chain
  function next(y) {
    // If y is passed (truthy), continue summing recursively
    if (y !== undefined) {
      return sum(x + y);  // recursive accumulation
    }
    return x;  // Termination: return the total sum
  }
  
  return next;
}

// ๐Ÿงช Test
console.log(sum(0)(1)(2)(3)(4)(5)());  // Output: 15
console.log(sum(5)(5)(5)());           // Output: 15
console.log(sum(10)());                // Output: 10

Problem Statement


๐Ÿ” Explanation

Step-by-step breakdown of sum(0)(1)(2)(3)(4)(5)():

  1. sum(0) returns a function next
  2. next(1) returns sum(0 + 1) โ†’ sum(1)
  3. Then sum(1)(2) โ†’ sum(3)
  4. ...
  5. Finally, the last call is sum(15)() where y === undefined
  6. It returns 15

โš ๏ธ JavaScript Note

if (y)

In your original code, this could be problematic if one of the inputs is 0 (because 0 is falsy). A safer condition would be:

if (y !== undefined)

Otherwise, something like sum(0)(0)(1)(2)() would not behave correctly. โœ…


๐Ÿ’ก JavaScript Interview Insight

This type of problem is popular in JavaScript interviews to test:

  • Closures
  • Currying
  • Recursion
  • Function chaining
  • Edge case handling (0, undefined, null, etc.)

๐Ÿงช More Test Cases

console.log(sum(1)(2)(3)());            // 6
console.log(sum(5)(10)(-3)());          // 12
console.log(sum(0)(0)(0)(1)());         // 1
console.log(sum(100)(200)());           // 300

๐Ÿ“ฆ Bonus: ES6 Arrow Version

const sum = x => y => y !== undefined ? sum(x + y) : x;

๐Ÿ’ฌ Want More?

Would you like to:

  • Extend this to multiply values? ๐Ÿค”
  • Collect values in an array instead of summing? ๐Ÿ“Š
  • Build a curried logger or validator function?

I can help with all of them โ€” just say the word! ๐Ÿ‘‡


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 Function Example
  • How to Create sum(1)(2)(3)...() in JavaScript
  • JavaScript Closure and Recursion Chaining
  • Implement Recursive Currying Function in JS
  • Chainable JavaScript Sum Function with Termination
  • Understanding Currying in JavaScript
  • JavaScript Functional Programming Example
  • Currying with Closures and Recursion
  • Lazy Evaluation in JavaScript
  • Advanced JavaScript Function Chaining Techniques

๐Ÿ“ข Hashtags for Visibility

#JavaScriptCurrying #FunctionChaining #ClosuresInJS #JavaScriptRecursion
#ChainableFunctions #AdvancedJavaScript #LearnJavaScript #CodeNewbie
#JSFunctionalProgramming #FrontendMasters #RecursiveFunctions #JSInterviewPrep #LazyEvaluationJS #JavaScriptTips #FrontendDevelopment #TechLearning #JavaScriptChallenges #CurryingWithClosures #JSCodingPatterns #SumFunctionJS