DEV Community

Discussion on: Currying in JavaScript

 
jwp profile image
John Peters • Edited

Thanks David I did some debugging today to figure this out.

 function sum(a) {
      return function (b, c) {
        return a + b + c;
      };
    }

    let mysum = sum(1);
    debugger;
    let mysum2 = mysum(2, 3);
    debugger;
Enter fullscreen mode Exit fullscreen mode

The results were:

As we can see, if a debugger wanted to know the value of mysum, in the console, they would only see it's a function as shown on far right side.

There's zero indication that this function when executed the 2nd time, has a preset value of 1 in it.

Now assume that mysum was set on entry to a module, but mysum2 was set much later. The developer is now wondering how mysum2 = 6...

mysum and mysum2 give no answers, but creating a de-composed form as shown in mysum3 kind-of, sort-of does help the debugger to understand.

This is what I was struggling with and why I mentioned an implicit state..

mysum is not a value, it's a function pointer! No values are returned until the 2nd and 3rd parameters are passed in. So this shows us that returning multiple functions forces a bit of thinking differently, as was said earlier it's composition of functions. Expressed in this syntax most clearly

let mysum3 = sum(1)(2,3);
Enter fullscreen mode Exit fullscreen mode

Indeed anonymous functions at that! I've seen this syntax before; but until now, didn't fully understand it.

Thanks!

Thread Thread
 
wulymammoth profile image
David • Edited

Ah! I love that your curiosity made you do a deeper dive! I went through something similar in other languages and honestly have never done currying or partial application in JS, although I've wanted to when I was spending most of my time in it.

Implicit state is always there, when you're working with a function that has had some arguments partially applied "earlier on". Does it make debugging more difficult? Yeah, it's not as easy as just shoving a break-point and inspecting current state. In languages, like Haskell, the lazy-evaluation becomes a challenge but yields performance gains. I work in Elixir which has nice facilities for this type of introspection, because it allows one to perform eager or lazy evaluation (Enum vs Stream) with the same functions in both modules

But I guess you're right, though -- that this idea (currying and partial application) isn't that useful in JS because it isn't the default paradigm that most of us are operating in. If employed, it would be analogous to using regexes everywhere and having to constantly explain them to everyone else. I very much like the ideas behind "functional reactive programming" ala RxJS where everything is a stream enabling some really really neat things one can do, but it is tough to get organizational buy-in when outside of some skunk-works team or small shop. But it is a powerful tool to maximize code reuse and a composition enabler in other languages and paradigms though