0

How does greaterThanTen(9) become the y variable in the return function? What I mean is how does the parameter (9) become the y in the return function argument? Wouldn't 9 be replaced with x since greaterThanTen = greaterThan(10)? Wouldn't the 9 just replace the x = 10 parameter? I just don't understand how that 9 parameter is getting to y in the return function.

 function greaterThan(x) {
   return function(y) {
     return y > x;
   };
 }

 var greaterThanTen = greaterThan(10);
 show(greaterThanTen(9));
eebbesen
  • 5,070
  • 8
  • 48
  • 70
Vodka_Tonic
  • 158
  • 3
  • 13

3 Answers3

4

It doesn't "become the y variable". The function greaterThan returns a function, and the value passed to greaterThan is "captured" in that returned function.

In other words, greaterThan(10) creates the following function:

function(y) { return y > 10; }

It's similar to writing:

function greaterThan10(y) { return y > 10; }

Functions that create functions take advantage of closures ("the thing that 'captures' the 10).

The advantage is that you don't need to keep writing greaterThanNnn functions for every number you want to use, you just call greaterThan(n) for whatever you need. This is a contrived, but popular, example, of course.

For chunks of info relating to referencing functions, when to use () and when not to, and some more realistic examples, see also:

Shazvan Hanif
  • 361
  • 3
  • 20
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Ok, your answer is really helping me understand this now. I think my problem is I'm not understanding what was happening in that return function. – Vodka_Tonic Jan 03 '14 at 03:14
  • @Vodka_Tonic It was returning ;) In JS, functions themselves can be values, like `42` or `"ohai"`. This is nice. – Dave Newton Jan 03 '14 at 03:16
0

when you called greaterThan(10) it assigned value of x and return the function in greaterThanTen variable which now becomes

var greaterThanTen = function(x){10>x};

then in next line you called greaterThanTen(9) so it will assign the x value. i hope you understood what i said.

Haider
  • 615
  • 1
  • 16
  • 38
0

You must have to know the basis about the closures concept in JavaScript. Closures are the most tricky and special addition to the JavaScript language. As you will notice they follow the lexical scope of the language flow. Here in this example;

 function greaterThan(x) {
   return function(y) {
     return y > x;
   };
 }

 var greaterThanTen = greaterThan(10);
 console.log(greaterThanTen(9));

If you see there is the main concept of closures. Once you call the function greaterThan it creates another function. But as you pass the first argument 10, it takes the place of x. Further when you call the function and pass the second argument 9 it takes place on y the function built inside. In this way the values are stored in the function call stack and you can compare and operate on those values.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129