2

I have seen in the past that you can do something like this:

function combine(arg1){
   return function(arg2){
      return (arg1 + arg2);
   };
}
combine("foo")("bar");

And the result will be "foobar".

You can of course do something like:

(function(x){
    return function(y){
       return x+y;
    };
})(2)(3);

With the result of 5.

I am simply wondering what this is called. I think I saw a small video of Crockford that I can't seem to find, I am sure it was on the Good Parts, that briefly talked about this. I also have the book and I can't see it in there.

It seems like just another way to invoke a function and control the scope of the variables.

Rchristiani
  • 424
  • 3
  • 18
  • 1
    "Chaining", maybe? I feel like it's something else though, although "chaining" *should* apply to the invocations. – Ian Apr 12 '13 at 20:18

4 Answers4

2

I believe you are looking for the word Currying

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • You know, I was thinking _currying_, but convinced myself OP was asking about the double invocation specifically. But _currying_ is absolutely correct. – Evan Davis Apr 12 '13 at 20:33
  • 1
    FYI: [Page 43](http://books.google.com/books?id=PXa2bby0oQ0C&q=curried#v=onepage&q=currying&f=false) in the book. – epascarello Apr 12 '13 at 20:34
1

Rchristiani, the video where Crockford references a function that adds from two invocations can be found on YouTube. It's part of a FrontEndMasters.com workshop series.

Test Your Knowledge of Function Scope with Douglas Crockford: http://youtu.be/hRJrp17WnOE

Crockford's site contains a copy of an excellent, and mind-blowing, breakdown of Currying. (I'm not sure who the original author is.) It shows examples of multiple invocations.

http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html

Rrrapture
  • 64
  • 1
  • 7
0

If you are referring to the ability of the inner function to access the variables from the outer function, this is called a closure.

You can read up closures here:
How do JavaScript closures work?

Community
  • 1
  • 1
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

What are you looking for is the Currying, or Partial (it depends if the functions takes more than two arguments or not).

You can actually do that also with bind, from ES5 specs. For instance:

function sum(a, b) {
    return a + b;
}

var sum5 = sum.bind(null, 5);

console.log(sum5(10)); // 15
ZER0
  • 24,846
  • 5
  • 51
  • 54