0
Explain please.
for (var x=1; x<10; x++){ x+=x; } console.log(x); //output 15 //if we console x inside for loop the output comes like for (var x=1; x<10; x++){ x+=x; console.log(x); } //output 2 6 14
11 ответов
+ 3
Safaa Alnabhan
The third statement of the loop, in your case the x++ is executed last.
So if you have this loop
for (var x = 1; x < 10; x++) {
x += x;
console.log(x);
}
It can be written like this
for (var x = 1; x < 10;) {
x += x;
console.log(x);
x++;
}
Notice that I move the x++ statement. So when the x reach 14, it will be written to the console, but the x++ statement is executed afterward, so the final value of x, 15, won't be written to the console
+ 2
Agent_I
I got a bit confused there thinking the `x++` instruction will only be executed when condition `x < 10` yields true. But a little test I did in several languages (having similar syntax) proves the output was the same.
+ 1
[Begin loop]
Let x be 1, repeat increasing x while x is less than 10
x += x // x is now 2 (1+1)
Is x less than 10? (Yes)
x++ // x is now 3 (2+1)
x += x // x is now 6 (3+3)
Is x less than 10? (Yes)
x++ // x is now 7 (6+1)
x += x // x is now 14 (7+7)
Is x less than 10? (No)
[Exit loop]
I hope this explains the original question above.
+ 1
Ipang thank you for answering .. the orginal question is about the first for loop why we got 15 not 14
0
For the second for loop I know how we get that result
x=1+1=2
x=2+1+3=6
x=6+1+7 =14
But why we get a different output when we console x outside the loop .. after looping x comes 14 that is bigger than 10 so we can't add 1 to the final result .. how did it become 15
0
This code shows what happens when you place the console.log inside a loop
0
//the same issue here and what about loop why we add x to x to 100 without any looping?
for(var x=1; x<10; x++){
x=x+x+100; console.log(x);
} //102
for(var x=1; x<10; x++){
x=x+x+100;
}
console.log(x); //103
0
Nico Ruder I didn't get what you meant
0
//the same issue here when we console x after looping x = 10 the output 10+10+100=120
var x=1;
for(x;x<10;x++){}
x+=x+100;
console.log(x);
//but when we console x inside for loop the final result of x = 9
var x=1;
for(x;x<10;x++){
console.log(x); } // 123456789
0
Ipang thank you for answering .. the orginal question is about the first for loop why we got 15 not 14
0
Ipang thank you for answering .. the orginal question is about the first for loop why we got 15 not 14