0

Though there is another post about closures my question is aimed at a specific block of code in order to make sure after reading the other linked post I was correct in my thinking.

I’m at the following code in the book

function greaterThan(n) {
  return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));

My question is how does the greaterThan10 function remember the value of n? Is this an example of closures?

Joe Horn
  • 21
  • 4
  • 2
    Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Nisarg Shah Jan 14 '18 at 06:14

1 Answers1

1

Yeah, it is an example of closures.

We have an inner function, wrapped inside the outer function greaterThan. Now here comes the interesting thing.

We are passing value to greaterThan(n) as :

var greaterThan10 = greaterThan(10);

Now just imagine for a second that the value is being help in this variable greaterThan10 i.e; 10 (assigned to first local variable 'n' in our case) .Now whenever you will use this variable and pass it a variable, it will automatically be assigned to the second local variable (m in our case). Now you can imagine the output which would be true.

You can do this deep down (three levels,four levels and so on), but the basics would be same.

Hope you understand :-)

Mohhamad Hasham
  • 1,750
  • 1
  • 15
  • 18