Currying and Closure
Consider this function:
Functions are values. Therefore, a function can return a function! This feature can be used in interesting ways!
What we have done with makeSundae
function is called currying in functional programming.
Currying is converting a function that takes arguments to return a chain of functions that each takes one argument.
Here is a more practical example
Notice the returned inner function retains access to the variables defined in the parent function even after the parent is out of scope. (Since the parent function has returned, our expectation demands that its local variables no longer exist. But, they do still exist!) This feature, in functional programming, is called closure.
Closure is when a function remembers and continues to access variables from outside of its scope.
Resources
-
For more examples, refer to MDN web docs, Closure.
-
If interested, freeCodeCamp has a good article "JavaScript Closures Explained by Mailing a Package".