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?
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.
+ 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}` );
+ 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)
+ 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);
+ 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)
- 1
Solo loop finishes at 5
Idk math to get it 7
But when it hits 3 x becomes 6