How do I understand a function that returns a function?

207 Views Asked by At

Here's the example code I'm struggling with:

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

var greaterThanTen = greaterThan(10);
show(greaterThanTen(9));

Is there a way to put it in math terms or follow the flow or something? I don't know why 10 is x and 9 is y.

5

There are 5 best solutions below

3
On BEST ANSWER

In the line:

var greaterThanTen = greaterThan(10);

You are assinging the variable x to the value 10 and then you store the function in the greaterThanTen Variable to be called later. this means that:

greaterThanTen = function(y) {
    return y > 10;
};

So when you do:

greaterThanTen(9);  #y = 9

You are calling:

return 9 > 10;
0
On

The greaterThanTen variable represents a function taking one argument and returning a boolean value whether this argument is greater then 10.

5
On

This function doesn't call a function, it returns a function.

This code is creating a new unary function where the original binary (greater than) operator's right-hand operand is prebound to a specific value.

In lambda calculus this binding is known as currying.

In Javascript the binding happens because the supplied value of the parameter x in greaterThan is permanently retained in the scope of the inner function (or "closure") that is returned.

So, when you call:

var greaterThanTen = greaterThan(10);

what you now have is a new function (named greaterThanTen) which always compares its single parameter to the bound value of 10.

Hence:

greaterThanTen(9);

will return false.

5
On
  • Create greaterThan(10)
  • Create function:
    function(y){return y > x}
  • return function.

So, when you call greaterThan(10), the function returns a function whose local variable x is set to 10.

var greaterThanTen = greaterThan(10) equals:
var greaterThanTen = function(y){return y > 10};

To finish, greaterThanTen(9) is called, which equals 9 > 10, which is false.

2
On

The only thing that greaterThan does is to set a value for x in

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

and store the resulting function in a variable name, in this case greaterThanTen, now with the contents

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

Calling greaterThanTen(9) is the same as looking at

function(y = 9) {return (y>10);}

which is the same as

function(y = 9) {return (9>10);}

which is false. Hence false is returned.

Edit:

Example of function that returns a function here: https://i.stack.imgur.com/3iKQA.jpg (x and y is switched around in y>x)

Namaste