0

What would be the difference between

var nums = [];
for (var i = 0; i < 10; ++i) {
nums[i] = i+1;
}

and

var nums = [];
for (var i = 0; i < 10; i++) {
nums[i] = i+1;
}

In the for loop, i = 0, but in the first iteration, would nums[i] = nums [0] or nums [1] since we are using ++i? How would the first iteration be different if i++ were used instead?

Update: For this particular for loop it doesn't matter. However, I'm interested to see a for loop where ++i vs i++ matters.

1
  • 1
    There is no difference. The first iteration in both would be nums[0]. Commented Aug 28, 2015 at 17:20

5 Answers 5

5

They would be exactly the same; ++i and i++ have the same effect on i, but the value of each expression is different; in this context, since the value is ignored, the code behaves the same.

As an example where switching between the two would matter, here is some truly awful code:

for ( var i=0; i++ < 10; )
Sign up to request clarification or add additional context in comments.

1 Comment

Can you provide a for loop in which i++ and ++i would matter?
2

++i increments before the "return", i++ increments after

var i = 0;
i++; //=> 0
i;   //=> 1

var j = 0;
++j; //=> 1
j;   //=> 1

For the purposes of your for loop, it doesn't make a difference.

Comments

0

In for loops, there is no difference. The difference between ++i and i++ is the value returned by the expression, but the expression is evaluated after each pass of the loop and you ignore the value.

Comments

0

There is no difference between the two. The incremented value will be ignoreed as it will happen at the end of the loop.

EDIT:

It makes no difference in the for loop if you write

for (var i = 0; i < 10; ++i) {

or

for (var i = 0; i < 10; i++) {

You will get the same results in both the cases. The reason why most of the people use i++ or better to say why i++ is more popular over ++i in a for loop is probably because people come from a habit of using i++ which was majorly used in C. Also to note that in C++ you can write your own version of ++ operator.

Comments

-1

They are the same. The increment occurs at the end of the body of the loop.

i.e. you can view the loop as

var i = 0;
while (i < 10) {

... Body of loop

i++ or ++i;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.