What is the difference between ++ i and i ++ in javascript

in my quest to learn and improve my JavaScript. I came across a script that has a switch / case statement, and I noticed that some variables are incremented using ++ with the variable before ++, and then some variables have + + after the variable. What is the difference between the two? Here's an example of what I'm trying to explain, notices the variables m and y.

switch(f){ case 0:{ ++m; if(m==12){ m=0; y++; } break; } case 1:{ --m; if(m==-1){ m=11; y--; } break; } case 2:{ ++y; break; } case 3:{ --y; break; } case 4:{ break; } } 
+8
javascript
source share
6 answers

++i returns the value of i after it has been incremented. i++ returns the value of i before the increment.

When ++ comes before its operand, it is called the "pre-increment" operator, and when it comes after it is called the post-increment operator.

This difference is only important if you are doing something with the result.

 var i = 0, j = 0; alert(++i); // alerts 1 alert(j++); // alerts 0 

It should be noted that even if i++ returns a value before the increment, it still returns a value after it has been converted to a number.

So,

 var s = "1"; alert(typeof s++); // alerts "number" alert(s); // alerts 2, not "11" as if by ("1" + 1) 
+32
source share

Same as any other c-style ++ increment.

foo = ++i same as:

 i = i + 1; foo = i; 

foo = i++ same as:

 foo = i; i = i + 1; 
+5
source share
 var i = 0; alert('i is ' + (++i)); // i is 1 // i is now 1 var i = 0; alert('i is ' + (i++)); // i is 0 // i is now 1 
+2
source share

In JS (as well as C, Perl, and perhaps a dozen other languages) I ++ operator increases I before it evaluates the operator, and I ++ increases it after. Same thing with -.

Example:

 var i=1; alert(i++); 

Will show "1", but:

 var i=1; alert(++i); 

Will show "2".

+1
source share

To illustrate, assuming:

 var a = 1; 

then

 var b = ++a; 

leads to

 true === (b === 2 && a === 2) 

but

 var b = a++; 

leads to

 true === (b === 1 && a === 2) 
0
source share

++ I am pre-increment, I ++ is post-increment.

If you only increase the variable and do not use the result at the same time, they are equivalent.

In this case, you really should use i + = 1 for readability (says Douglas Crockford ..)

0
source share

All Articles