Carl Edwards
Carl Edwards

Reputation: 14454

Passing multiple arguments to curried functions

I'm currently reading the book, Effective Javascript and have reached the chapter regarding closures. There's an example that illustrates how to pass the argument of a nested function as so:

function sandwichMaker(magicIngredient) {
  function make(filling) {
    return magicIngredient + " and " + filling;
  }

  return make;
}

var hamAnd = sandwichMaker("ham");

hamAnd("swiss"); // ham and swiss

But if I were to pass two arguments (one for the initial function, the second for the nested function) I get undefined for the second parameter:

sandwichMaker("ham", "swiss"); // ham and undefined

Do I always need to declare a variable first then provide the second argument once I want to invoke it?

Upvotes: 0

Views: 420

Answers (2)

robbyphillips
robbyphillips

Reputation: 971

Since sandwichMaker returns a function, the actual call that you're looking for is sandwichMaker("ham")("swiss");

Remember that without the parentheses following the name, a function will behave just like any other variable in that you can pass it around without actually evaluating or "running" it.

So, return make; gives you a function that you can evaluate at a later time, while return make(...); gives you the value of evaluating make.

Upvotes: 1

Moti Korets
Moti Korets

Reputation: 3748

If you want to pass a parameter to the second function without storing it in a variable you can do it like this

sandwichMaker("ham")("swiss");

Upvotes: 0

Related Questions