Raven - Blog
April 8, 2022

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 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:

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 :

Check this with JS…

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);
function timer(secondes) {
    if (secondes > 0) {
        console.log(secondes);
        timer(secondes--);
    }
}

timer(10);

If you are interested, these notations come directly from mathematics: Wikipedia

Follow me

Subscribe to my RSS feed !