2

Why this code returns 43 as the result, I expect it to result 42. The code is as follows:

function say667() {
  // Local variable that ends up within closure
  var num = 42;
  var say = function() { console.log(num); }
  num++;
  return say;
}
var sayNumber = say667();
sayNumber();
Umar
  • 990
  • 1
  • 8
  • 19

1 Answers1

4

You've closed over the variable num, not the value the variable has at the time you define the function.

This is the order of events:

  1. You assign 42 to num
  2. You increment num to 43
  3. You return a function and store it in sayNumber
  4. You call that function, which reads the value of num, which is 43
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335