-1

I have two questions regarding the following code sample:

function greaterThan(n) {
  return m => m > n;
}
let greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
//returns true

From what I understand the function greaterThan(n) returns a function which takes the parameter m but here it starts to get tricky for me:

  1. Why is this m not declared and still properly working within this code sample?
  2. greaterThan10 is declared as a variable in line 4 and it is inheriting the value of greaterThan(10). How can it behave like a function in line 5, where this "variable" takes another integer?
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 3
    "*returns a function itself which is called m*" no, the parameter it takes is called `m` – VLAZ May 04 '22 at 15:45
  • "*How can it behave like a function in line 5*" you already said it: "*the function greaterThan(n) returns a function*" – VLAZ May 04 '22 at 15:46
  • `m` is declared on the left hand side of the `=>` (i.e. as the name of the only parameter the function takes). – Quentin May 04 '22 at 15:47
  • 1
    Are you familiar with _arrow function_ syntax? `m => m > n` is a valid function in its own right. – jonrsharpe May 04 '22 at 15:47
  • That arrow function is equivalent to `function(m) { return m > n; }`. Does that help? – Barmar May 04 '22 at 15:47
  • `the function greaterThan(n) returns a function which take the parameter m`... no, the greaterThan function accepts m as an _input_ value, and then it then returns a function, which itself (when called) returns a boolean (true/false) which is the result of calculating whether m is greater than n or not – ADyson May 04 '22 at 15:49

1 Answers1

0

greaterThan is a higher order function; it returns another function that it creates based on the inputs.

m => m > n is an arrow function.

It's equivalent to this:

function greaterThan(n) {
  return function (m) {
    return m > n;
  }
}
let greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
//returns true
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34