1

I am trying to understand how javascript function returns function handle and why following code prints '2' instead of '1'

var num = 01;
function processAndIncrement() {
  var process = function() { 
    console.log(num); 
  }
  num++;
  return process;
}
var proCall =  processAndIncrement();
proCall();
  • 1
    Yes, it returns a function handle. Which, when called, will output the current value of `num`. What in particular do you not understand about that, why did you expect it to log `1` (and never increment)? – Bergi Dec 03 '17 at 17:09
  • The call to `processAndIncrement` increments `num` (which is a global variable) and return another function that logs `num` (which is now `2`). – ibrahim mahrir Dec 03 '17 at 17:10

2 Answers2

1

The num variable is independent of the functions in your code. Both functions refer to the same variable, so they both mutate the same data and observe the changes.

So the num++ operation increments num before proCall is ever invoked. When proCall is finally invoked, it sees the incremented state of num, because it has already been incremented.


Here's a step-by-step description of the order of operations (ignoring hoisting). Follow the sequence of numbers.

// 1. create the variable
var num = 01;

// 2. create the processAndIncrement function
function processAndIncrement() {

  // 4. Assign a function that logs `num` to the `process` variable
  var process = function() { 

    // 8. log the current value of `num` (which was incremented at step 5)
    console.log(num); 
  }

  // 5. increment `num`
  num++;

  // 6. return the `process` function
  return process;
}

// 3. Invoke processAndIncrement, and assign its return value to `proCall`
var proCall =  processAndIncrement();

// 7. invoke `proCall` (which is the same as the `process` function)
proCall();

If you wanted the increment to happen when proCall is invoked, then num++ should be moved to be inside the process function.

1

The Code prints 2 because you increment num which's value is already 1 (01 == 1).