Alex Rivera | Logout

javascript i++ vs ++i

Asked 2011-07-29T02:01:01.337
151

In javascript I have seen i++ used in many cases, and I understand that it adds one to the preceding value:

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

But what happens when I do this:

++i;

And is it any different using the -- operator (besides of course that it's subtraction rather than addition)?

Edit
Report

1 Answer

9

It determines whether the increment happens before or after the value of the variable is used.

var j = 2;
console.log(j++);   // 2
console.log(j);     // 3

var k = 2;
console.log(++k);   // 3
console.log(k);     // 3
answered 2011-07-29T02:03:53.600

Your Answer