Facebook Pixel

How the sum(1)(2)(3) Function Uses Closures

Deep dive into how closures make the curried sum work.

How the sum(1)(2)(3) Function Uses Closures

The curried sum function relies on closures to accumulate the total.

The Code

function sum(a) { return function (b) { if (b !== undefined) return sum(a + b); return a; }; }

Closure Analysis

  1. sum(1) is called. a = 1. Returns a function that closes over a.
  2. The returned function is called with 2. b = 2. b !== undefined, so it returns sum(1 + 2) = sum(3).
  3. sum(3) is called. a = 3. Returns a new function that closes over a = 3.
  4. The returned function is called with 3. b = 3. Returns sum(3 + 3) = sum(6).
  5. sum(6) is called. a = 6. Returns a function.
  6. Called with no argument. b = undefined. Returns a = 6.

Each Call Creates a New Closure

Each call to sum creates a new function with a new closure over a new a. The previous closure is replaced by the new one, but the accumulated value is passed forward.

The Takeaway

The curried sum uses closures: each sum(a) call creates a function that closes over a. When called with b, it returns sum(a + b), creating a new closure with the accumulated total. When called with no argument, it returns the accumulated a.

Each call to sum(a) returns a function that closes over a. When called with b, it returns sum(a + b), creating a new closure with the accumulated total. The closure keeps the running sum alive between calls.

Yes. Each sum(a) call creates a new function with a new closure over a. The previous closure is replaced, but the accumulated value (a + b) is passed forward to the new sum call.

b is undefined. The function checks if (b !== undefined), which is false. It returns a (the accumulated sum). This is how the chain terminates and the result is retrieved.

No. The curried sum requires each returned function to remember the accumulated total. This is only possible with closures. Without closures, the inner function would not have access to the previous arguments.

O(n) where n is the number of chained calls. Each call creates a new function and closure. The space complexity is also O(n) due to the call stack (unless tail-call optimization is available, which it is not in most JS engines).

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.