Search code examples
javascriptreturncurrying

Return statements with currying techniques


While learning with FreeCodeCamp I'm faced with a question about currying.

The solution was this:

function add(x) {
// Add your code below this line
return function(y) {
  return function(z) {
    return x + y + z;
    }
  }
}
add(10)(20)(30);

However, I'm confused as to why the return statements here aren't terminating the execution of the function?

I was under the impression that as soon as you use a return statement, that line would be executed and everything beyond that would be ignored.


Solution

  • It ends only the own function. The returned function isn't called yet.

    function add(x) {
        return function(y) {      // \
            return function(z) {  //  |
                return x + y + z; //  | part of the returned function
            };                    //  |
        };                        // /
    }
    
    add(10)(20)(30);