0
Why does one script starts with 0 and ends with 4 while the other starts with 1 and ends with 5
for(i=0; i<5; ++i) { document.write(i); } // Output : 01234 for(i=0; i<5; ) { document.write(++i); } // Output : 12345
6 Réponses
+ 3
Hopefully you read the lesson and are still stuck.
The first loop, ++i is done at the end of the loop. See below (comments in brackets):
First time through loop
1. for i=0 (i initialised to 0)
2. i<5 (returns true so code keeps going)
3. document.write(i) (the value of 'i' which is still 0 is written)
4. ++i (value of 'i' incremented by 1)
Next time through loop
1. i<5 (true)
2. document.write(i) (i is still 1)
3. ++i (i is now 2)
The above continues to write i as 2, 3 and 4, then
1. i < 5 (false so loop ends).
So essentially, because the value of i is incremented at the end of the loop, the fact that it's using a preincrement has no impact. If you wrote the loop with i++ you'd get the same result. The only time I believe a preincrement makes a difference is where it's used on the same line of code as something else.
+ 5
Because in the second loop you use pre-increment operator on variable 'i' (++i). This increments value of 'i' before the value is printed on screen. Hope it's clear enough : )
Hth, cmiiw
+ 3
Look at this line:
document.write(++i);
The pre-increment operator is used before 'i', meaning "increment value of 'i' before we print it on screen". As you see on first iteration value of 'i' is zero, incremented by the operator it becomes one, then it is printed on screen.
To see the difference, between pre-incremented and post-increment operator change the line:
document.write(++i);
into;
document.write(i++);
You will see a different output : )
+ 1
Then why does it end at 5 and not 4. It's a < symbol and not a =< symbol....
+ 1
Check out this part of the JS lesson.
https://www.sololearn.com/learn/JavaScript/1140/
As you go through the lesson you will see that
“Statement 3 is also optional, and it can be omitted if you increment your values inside the loop.”
In the first loop, 'i' is not incremented until after 'document.write' so starts at 0.
In the second loop, 'i' is incremented before 'document.write'
0
Can you explain to me the first loop? shouldn't 1 be added to 0 since its a pre increment