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.

1

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Searching on [javascript] 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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.