Let's increment !
Posted on April 8, 2022 • 2 minutes • 252 words • Other languages: Français
In computer development, a basic notion present in all or almost all languages is the increment and its opposite the decrement. For the uninitiated, this means adding 1 or removing 1 from a variable by using a specific operator which is usually :
++
: for incrementing--
: for decrementing
For example, in JS :
let x = 1;
x++; //x++ is the same as x + 1
But although this concept and its operator are known to everyone, fewer people have identified that there are actually two concepts:
- The post-increment
- The pre-increment
So what is the difference ? Well, the difference will be the return value ! In the case of pre-incrementing, the returned value will be the one before incrementing. In concrete terms this gives :
- Post-increment :
y = x++
is the same asy = x ; x = x + 1
. - Pre-increment :
y = ++x
is the same asx = x + 1 ; y = x
Check this with JS…
- Post-increment :
- Pré-increment :
A more concrete example ? Let’s take this piece of code that displays a counter, if you do a post-increment on the variable seconds
you get an infinite loop… with a pre-increment, your program will work :
function timer(secondes) {
if (secondes > 0) {
console.log(secondes);
timer(--secondes);
}
}
timer(10);
- Post-increment generating an infinite loop:
function timer(secondes) {
if (secondes > 0) {
console.log(secondes);
timer(secondes--);
}
}
timer(10);
If you are interested, these notations come directly from mathematics: Wikipedia