var counter = 0;
var increment = function(){
return counter++;
// return counter=counter+1;
}
console.log(increment());
Why does counter ++; returns 0 but counter = counter +1; returns 1?
var counter = 0;
var increment = function(){
return counter++;
// return counter=counter+1;
}
console.log(increment());
Why does counter ++; returns 0 but counter = counter +1; returns 1?
The post-fix increment operator returns the current value for evaluation and then increments it, so the value change is noticeable when it is referenced for the second time.
So when the return
statement is executed, the value has not yet been incremented. You can cross-check by doing the following:
console.log(counter++); // 0
console.log(counter); // 1
return counter; // obviously 1
Try the pre-fix operator which increments and then returns the incremented value to be evaluated.
return ++counter; // 1
This is called prefix (++x
) vs postfix (x++
) and the only difference is really the order of operations:
counter;
evaluates to a value. (0)
counter++;
evaluates to a value (0), performs a calculation (0 -> 1) and modifies a variable (counter
-> 1).
++counter;
performs a calculation (0 + 1), modifies a variable (counter
-> 1) and evaluates to a value (1).
var counter = 0;
var increment = function(){
// now counter is 0 and after return it increment it's value to 1
// return 0 then 0+1=1;
return counter++;
// calculate like math, counter = 0+1 then counter = 1, now return 1;
// return counter=counter+1;
}
console.log(increment());
In first scenario,
return counter++;
This statement is postfix, and evaluates like
return 0; and then 0+1=1
In second scenario,
return counter=counter+1;
Calculate like math,
return counter = 0+1 then,
return counter = 1,
return 1;