whats the difference
The difference is how it is evaluated.
++x
, we are using the Prefix incrementor, which increments the value and then returns the result.x++
is the Postfix incrementor, which returns the value ofx
and then performs the increment.
let num = 0;
console.log(`Num is ${num}`);
// "Num is 0"
console.log(`Prefix increment (++num): ${++num}`);
// "Prefix increment (++num): 1"
console.log(`Num is ${num}`);
// "Num is 1"
// but watch what this does:
console.log(`Postfix increment (num++): ${num++}`);
// "Postfix increment (num++): 1"
// but while that shows 1, `num` is now 2!
console.log(`Num is ${num}`);
// "Num is 2"
This is taken from the official docs:
If used postfix, with operator after operand (for example,
x++
), the increment operator increments and returns the value before incrementing.If used prefix, with operator before operand (for example,
++x
), the increment operator increments and returns the value after incrementing.
3 Likes
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.