Question:
The most common and known form of increment is the post:
for (var i = 0; i < 10; i++){
console.log(i);
}
However, I see the pre-decrement below:
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 variable in JavaScript?
What gains can these differences bring?
Answer:
Pre-increment
See the example below: in pre-increment, 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 7. Only after that, the variable – which is already worth 7 – is assigned to 'd', which is also set to 7.
Post-Increment
See in the example that the variable is first 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 assigned to d
, which is also worth 6. Only after this operation does c
have its value increased, then being 7.
The same rule applies to decrements
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 example pre- or post-increment will always result in the same result , since there is no assignment of the value of i
to another variable, you are just returning the value of i
after the increment operation, be it pre or post.
This way your example works exactly like:
c = 6;
c++; // o valor de 'c' é 7
console.log(c); // retornará 7
Where
c = 6;
++c; // o valor de 'c' é 7
console.log(c); // retornará 7