Why 7 instead of 6 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why 7 instead of 6

For(var x =1; x<6;x++) If (x==3) X=6; Alert(x) Output is 7 Why would not it be 6?

2nd Mar 2022, 1:29 AM
Evgeny Sergeev
Evgeny Sergeev - avatar
6 Answers
+ 4
Because x keeps iterating and the loop ends when x is greater than 6, and because you defined x as a global variable, it is available outside of the loop block.
2nd Mar 2022, 1:51 AM
Solo
Solo - avatar
+ 4
Adding printouts and brackers might help understanding the code for( var x =1; x < 6; x++ ) { if (x == 3) { x = 6; } console.log( `in loop x = ${x}` ); } console.log( `out of loop x = ${x}` );
2nd Mar 2022, 2:44 AM
Ipang
+ 3
Evgeny Sergeev Answer would be 6 if there is break after x = 6 otherwise answer would be 7 because of x++ for(var x = 1; x < 6; x++) if (x == 3) { x = 6; break; } alert(x)
2nd Mar 2022, 3:05 AM
A͢J
A͢J - avatar
+ 2
You reminded me of the joke about the eighth railway carriage 😃 - this is the one that immediately goes after the seventh, or the one before the ninth 🤣 Here is the sequence of the for() loop, check it out ☺️: var x = 1; for(; x < 6 ;){ if(x == 3) x = 6; x++; } alert(x);
2nd Mar 2022, 2:07 AM
Solo
Solo - avatar
+ 1
X = 7 because When x = 3 You entered the if block, there x becomes 6. But, the for loop was running at that time. So the value of x get incremented at the end of for loop. That's why x becomes 7 /*********************************/ If you want the value of x = 6 Then use a break statement Write this way if(x==3) { x = 6; break; // the loop will terminate here immediately and value of x will not increment } Alert(x)
2nd Mar 2022, 4:30 AM
NonStop CODING
NonStop CODING - avatar
- 1
Solo loop finishes at 5 Idk math to get it 7 But when it hits 3 x becomes 6
2nd Mar 2022, 1:57 AM
Evgeny Sergeev
Evgeny Sergeev - avatar