1

In chapter 5 of Eloquent Javascript (https://eloquentjavascript.net/05_higher_order.html) there is an example that I'm having a hard time wrapping my head around.

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

I get the initial call of the function and assigning n to 10. It's when it's called a second time I don't understand how 11 would get passed to the variable m (wouldn't the parameter still be n? I almost want to think it would overwrite 10 with 11).

When I do alert(greaterThan10) it shows m => m > n which I was also confused as to why it wouldn't show n as 10.

Barmar
  • 741,623
  • 53
  • 500
  • 612
onetap
  • 455
  • 1
  • 5
  • 8
  • 3
    That `return m => m > n` is (more or less) equal to `return function(m) { return m > n; }` – Jonas Wilms Nov 06 '19 at 21:07
  • `greaterThan` returns a function (`m => m > n`). `greaterThan10` is said function; a function that takes one parameter `m`. – deceze Nov 06 '19 at 21:10
  • The closure doesn't replace the function body, it just saves the scope where `n == 10`. Use `console.dir(greaterThan10)` and look in the `[[Scopes]]` property to see this. – Barmar Nov 06 '19 at 21:11
  • thanks, I think the arrow function was throwing me off – onetap Nov 06 '19 at 21:13

0 Answers0