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