While most of us know and use the
-- operator in our code which when used, adds 1 in the case of ++ and deducts 1 if -- but there is a subtle caveat when it comes to its position in the code that I thought is worth noting.
let age = 0; console.log(age) // expected output 0 console.log(age++) // expected output 0 console.log(age) // expected output 1
This means given that age initially had the value 0, age++ will first return 0 and then age will be incremented to 1. Here's a step-by-step breakdown:
- age has an initial value of 0.
- age++ returns the current value of age, which is 0.
- After the operation, age is incremented to 1. That's why age++ returns 0 when age initially has the value 0.
If you were to use the pre-increment operator for the same code
++age it would first increment age and then return the incremented value, so ++age would return 1 in this case.
Understanding the subtle difference of where we position this operator greatly helps in avoiding annoying bugs.
the same example using pre-increment:
let age = 0; console.log(age) // expected output 0 console.log(++age) // expected output 1 console.log(age) // expected output 1
The same rule applies to the -- operator.