# Differences between x ++ and ++ x in JavaScript [duplicated]

7

What are the differences between these two expressions?

`x++` and `++x`

This is the code I was trying to understand:

``````var x=1, y=1, z=0;
do{
z=x+y;
console.log("z= "+ z);}

while(++x<=1 && y++>1);
console.log ("++x="+x + " y++="+y);
z+=x+y;
document.write(z);``````

NOTE: I have found this same question but answer for Java and I do not know if the answer is correct for JavaScript

asked by àngelv 05.09.2017 в 11:44
source

11

The operator `++` does the same: increase the value.

The only difference is that if the operator appears before the variable, the value is modified before evaluating the expression.

Visual example:

``````let a = 0;
let b = 0;
let i = 0;

while ( i < 5 ) {

console.log('Variable a: ' + ++a );
console.log('Variable b: ' + b++ );

console.log( 'Iteración #' + i );
console.log( '-----------' );

i++;
}``````

9

`x++` executes the instruction and then increases the value.

`++x` increases the value and then executes the instruction.

``````var x = 1;
var y = x++; // y = 1, x = 2
var z = ++x; // z = 3, x = 3
``````

• `f(n++)` is the same as `f(n); n=n+1;`
• `f(++n)` is the same as `n=n+1; f(n);`
• `b=n++ > 1` is the same as `b=n>1; n=n+1;`
• `b=--n;` is the same as `n=n-1; b=n;`