๐ 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()
orvalueOf()
๐ป 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:
- Closure:
total
is preserved across chained calls. - Function returning itself:
next()
returnsnext
, enabling further chaining. - Coercion with
.toString()
: JavaScript converts the function into a primitive value usingtoString()
when used in a string context (likeconsole.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
andtoString
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