1

I am trying to pass an argument to a function within a function;

function add() {
  let x = arguments[0];

  function s(num) {
    return num + x;
  }
}

add(2)(3) //second argument to be passed to 'function s'.

so im wanting the call to return 5.

What is the best approach to this? thanks in advance.

tygar
  • 244
  • 1
  • 4
  • 15
  • Possibly a duplicate of [*Function to accept variable number of chained calls like `add(1)(2)(3)(4)`*](https://stackoverflow.com/questions/45162228/function-to-accept-variable-number-of-chained-calls-like-add1234). – RobG Aug 09 '17 at 01:41

1 Answers1

1

Currying is the name of the construction that allows you to partially apply the arguments of a function. It means that instead of passing multiple arguments to a function and expect a final result, you can pass a subset of this arguments and get back a function that is waiting for the rest of the arugments.

As already pointed by @KevBot, your example is missing the return of the second function and would be:

function add() {
  let x = arguments[0];

  return function s(num) {
    return num + x;
  }
}

add(2)(3);

ES6 Curryed Hello World:

curryedHelloWorld = (greeting) => (name) => `${greeting}, ${name}!`;
curryedHelloWorld("Hello")("Tygar");

You can even uncurry the curryedHelloWorld example making it the opposite way:

helloworld = (greeting, name) => curryedHelloWorld(greeting)(name);
helloworld("Hello", "Tygar");
André Teixeira
  • 2,392
  • 4
  • 28
  • 41
  • Searching on [*`[javascript] currying`*](https://stackoverflow.com/search?q=%5Bjavascript%5D+currying) returns over 1,000 results, surely one suits as a duplicate? It's not clear to me if the OP wants currying or chaining. Perhaps [*Variadic curried sum function*](https://stackoverflow.com/questions/5832891/variadic-curried-sum-function)? – RobG Aug 09 '17 at 01:44