tygar
tygar

Reputation: 264

Passing arguments to a function within a function - javascript

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.

Upvotes: 1

Views: 96

Answers (1)

André Teixeira
André Teixeira

Reputation: 2562

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");

Upvotes: 1

Related Questions