What is the difference between pre and post increment in Javascript?

Asked

Viewed 6,633 times

20

The most common and known form of increment is the post:

for (var i = 0; i < 10; i++){
    console.log(i);
}

However, I then see the pre-decrease:

for (var i = 0; i < 10; ++i){
    console.log(i);
}

However, the results are the same for this example.

What are the differences between pre- and post-increment/decrement of a Javascript variable?

What gains these differences can bring?

4 answers

18


Preincrement

See the example below: in the preincrement, first the variable c is incremented, and only then assigned to d:

var c, d;
c=6;
console.log("Pre-incremento\n");
console.log("Numero sem incremento: %d\n", c); // 6
d=++c; // O VALOR É INCREMENTADO, E SÓ DEPOIS PASSADO PARA 'd'
console.log("Valor de 'c':%d\nValor de 'd':%d\n", c, d); // c = 7, d = 7

In this example, c, which is worth 6 is first incremented and becomes worth 7. Only after that, the variable - which is already worth 7 - is assigned to’d', which is also worth 7.

Post-increment

Note in the example that first the variable is assigned, and only then incremented:

var c, d;
c=6;
console.log("Pos-incremento\n");
console.log("Numero sem incremento: %d\n", c); // 6
d=c++;// O VALOR É PASSADO PARA 'd', E DEPOIS INCREMENTADO
console.log("Valor de 'c':%d\nValor de 'd':%d\n", c, d); // c = 7, d = 6

In this example, c, which is worth 6 has its value attributed to d, which is worth 6 also. Only after this operation that c has its value increased, then worth 7.

The same rule applies to Decrees

Pre-decrement

var c, d;
c=6;
console.log("Pre-decremento");
console.log("Numero sem incremento: %d", c); // 6
d=--c; // O VALOR É DECREMENTADO, E SÓ DEPOIS PASSADO PARA 'd'
console.log("Valor de 'c':%d\nValor de 'd':%d\n", c, d); // c = 5, d = 5

Post-decrement

var c, d;
c=6;
console.log("Pos-decremento");
console.log("Numero sem incremento: %d", c); // 6
d=c--; // O VALOR É PASSADO PARA 'd', E DEPOIS DECREMENTADO
console.log("Valor de 'c':%d\nValor de 'd':%d\n", c, d); // c = 5, d = 6

Therefore

In your pre or post-increment example will always result in same result, as there is no attribution of the value of i to another variable, you are just returning the value of i after the increment operation, whether pre or post.

In this way your example works exactly as:

c = 6;
c++; // o valor de 'c' é 7
console.log(c); // retornará 7

or

c = 6;
++c; // o valor de 'c' é 7
console.log(c); // retornará 7

9

The behavior of these increment operators is related to something I mentioned in my answer to How does this if/Else work with "?" and ":"?.

Imagine a line containing only this:

i;

We say it doesn’t do anything and it doesn’t do anything, right? But this is valid in the language, so it is somehow interpreted according to the rules of the language (leaving aside that there may be mid-way optimizers simply discarding this line of code). The language interprets i as a expression, and expressions always result in something. In the case of our above line, assuming that i does not exist, the result of the expression would be undefined.

Maybe it’s already clear what I’m getting at: i++ and ++i are also expressions (composed of the expression i and one of the operators ++ – are two, one used as prefix, and the other as suffix). And so they result in a value, which can be used in another expression that encompasses this, as an assignment:

var i = 0;
var x = i++;
var y = ++i;

And the difference between operators is precisely in the behavior of the result of the expression: while i++ returns the value of i before the increment, ++i first increment i, and then returns its value. So, in my example above, the value of x will be 0, and that of y will be 2.

Taking your examples from:

for (var i = 0; i < 10; i++){

and

for (var i = 0; i < 10; ++i){

The result of expressions i++ and ++i is different, but is not used. What is used, and only in the next line, is the i. And the effect of the two variants on i at that moment (next row) is equivalent.

  • I noticed it’s getting more common to find ++i in loops than the "classic" post. Does that have a reason? Any personal taste of certain programmers? Maybe aiming for some maintenance? (or maybe it’s just me)

6

You will only notice difference when making use of the increment result, example:

var i = 1;
i++;
console.log(i == 2); // true
// é o mesmo que
var i = 1;
++i;
console.log(i == 2); // true

//No exemplo abaixo não
var i = 1;
console.log(i++ == 2); // false
var i = 1;
console.log(++i == 2); // true

When used in a loop, as in your example, there is no difference, because i++ returns i and adds 1, and ++i adds 1 to the value of i and returns it, so in the first iteration, the two will have the same value.

As for optimization, the pós-incremento makes use of a temporary variable to store the value of i before the increment, the pré-incremento adds the value to the original variable, however this is a premature optimization and according to this article, statistically insignificant.

  • 1

    +1 for the good answer, and I would love to give another positive vote for the reference to Article.

  • 1

    is.. as far as I can see, the optimization should be 1 or 2 options.. unnecessary micro-optimization.

-1

1 - I believe that using "FOR" will be a little difficult to understand increment work. Try with while (it becomes clearer)

2- it is better to use the increment in a variable the part, following example:

{
    int i = 0;
    int var = 0;
    while (i < 10) {
        //var += ++i;
        var += i++;
        System.out.println("i= " + i + " | var= "+var);
    }

By changing the increment to "var" Voce you can notice that even with var++ before the print method the printed value will be [var = 0] q means that the variable changes after the loop is executed. Falow... Valews!

  • 1

    The question is specifically about Javascript, not Java.

  • And there’s something wrong there...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.