Each method closes over the current value (a). add returns calc(a + b), which creates a new calc with the new value. The closure keeps the value alive between chained calls.
How does the extended sum use closures?
More FAQs in sum(1)(2)(3) with Add and Subtract Operations
Return an object with methods: function calc(a) { return { add: b => calc(a + b), subtract: b => calc(a - b), result: () => a }; }. Each method returns a new calc with the updated value. result() returns the final value.
The chain pattern (also called fluent interface or method chaining). Each method returns a new object with the updated value, allowing methods to be chained: calc(5).add(3).subtract(2).result(). Similar to jQuery and lodash.
Call the result() method: calc(5).add(3).result() returns 8. The result method returns the accumulated value and terminates the chain.
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.