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

3 answers

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++;
}
    
answered by 05.09.2017 в 11:54
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
    
answered by 05.09.2017 в 11:48
4

Both Java and Javascript have an inheritance syntax of C / C ++, so yes, the behavior is the same in all these languages: ++ before it indicates that the increment is done first, and if it is set after it indicates that it is first does the rest of operations (comparisons, assignments, passing parameters ...)

  • f(n++) is the same as f(n); n=n+1;
  • f(++n) is the same as n=n+1; f(n);

The same applies to conditions or assignments:

  • b=n++ > 1 is the same as b=n>1; n=n+1;
  • b=--n; is the same as n=n-1; b=n;
answered by 05.09.2017 в 11:49