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.