Can anyone explain me this code?

Hi there!

I am trying to figure out this example:

function greaterThan(n) {
return m => m > n;

let greaterThan10 = greaterThan(10);
// true

it seems like when I create greaterThan10 and I pass it 10, this value is “stored” somewhere
then when I call greaterThan10(11) 11 is compared to the previous value 10, returning true
but why does this work?? how??

Thank you!

That code is similar to the following:

function greaterThan(n) { // outer function
  return function (m) { // inner function
    return m > n;

When the inner function is returned out of the greaterThan function, the inner function retains knowledge of variables from the outer function.

var gt10 = greaterThan(10);
// The gt10 function retains knowledge of the n variable.

Inner functions can access variables of outer functions, even when that inner function has been returned from the outer one. It’s a technique called closure, that involves lexical scoping.

gt10(20); // true
gt10(8); // false

Thank you Paul!
I am starting to understand closures. I think my problem is more with the arrows.
The same code written by you is clear, but it was not clear written in => format
But is there an order in the parameters? I mean the first time when you define gt10 you are passing n from what I understand. But when you actually use gt10 you pass another single parameter, which goes straight into m?

I wrote something about arrow notation a short time ago that you might find useful, working through the different function notations.

The gt10 function is shown below, and has the number 10 assigned to the n variable.

function (m) { // inner function
    return m > n;

When you call the g10 function, it already knows about the n variable. You are only giving it what it needs for the m variable. For example with gt10(7) the m parameter of the function ends up being the number 7.


Essentially, there are two stages to the code.

I personally would call greaterThan a generator. It generates functions based on the parameter it’s given. Note that the generator takes exactly 1 parameter, n.

Stage 1: Generate Function.
var gt10 = greaterThan(10);
We execute the generator code, giving it an argument for n, 10. It returns function code.
gt10 is now a function, that in effect, reads as:

function gt10(m) {
    return m > 10;

This generated function only takes 1 parameter: m, and compares it to 10.

Stage 2: Execute function.

This now passes 20 into our gt10 function, which, quite understandably, returns True.


Thank you Paul!
Now it’s clear.

Thank you m_hutley! You and Paul really helped me!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.