0

I have a question about currying function which is returning the value from if statement, any time it has been called after first call.

I know that this is a currying function but don't understand, how the value has been saved in the let variable for the next consecutive calls? This doesn't make any sense for me.

I also don't understand the anonymous function passed as a first argument and another anonymous function used in the body.

Why the function call is happening with one brackets like this test(), instead test()()?

Can somebody explain this complicated peace of code?

const test = (() => {// <--- why is it passed as an argument?
  let variable = null; // <--- how on second call let variable is not empty and has the value in it???

  return () => {
    // <--- what is the role of this return empty function?
    if (variable) {
      console.log("returning in the if statement");
      return variable;
    }

    variable = "parrot";

    console.log("returning at the bottom");
    return variable;
  };
})(); // <--- is this still a currying function?

test();
test();
test();

Output:

returning at the bottom
returning in the if statement
returning in the if statement
Sonny49
  • 425
  • 3
  • 18
  • 1
    There's no currying there. That's an immediately-invoked function expression that declares a `let` variable that's persistent over all calls of `test`, but not visible outside. It's nearly equivalent to `let variable = null; const test = () => { if (variable) { ...` except that there's no way to access `variable` outside. – CertainPerformance Sep 21 '22 at 02:27
  • ahh ok got it, thank you a lot for clarification. could you please share your opinion what is the benefits of using the code above? Because after your explanation I think that it is overcomplicated for no reason. – Sonny49 Sep 21 '22 at 02:36
  • 1
    It can make it clearer that there's *absolutely no way* for the `variable` to be accessed or modified outside, which is potentially useful though arguably overly defensive sometimes - but there are usually better ways to accomplish that with ES modules – CertainPerformance Sep 21 '22 at 02:37
  • Can memoization be an alternative? – Sonny49 Sep 21 '22 at 02:39
  • 1
    Don't know what you mean by an alternative - the code in the question *is* effectively memoization – CertainPerformance Sep 21 '22 at 02:41

0 Answers0