+ 12
How does a for loop behave in JS when we call the varriable outside the curly braces?
Please explain the logic, I am confuse, it behaves strangely :( for(x=0;x<6;x+=2){} Console.log(x) //6 _____________________ for(x=1;x<6;x+=2){} Console.log(x) //7 ______________________ for(x=2;x<6;x+=2){} Console.log(x) //6
9 Réponses
+ 5
Well, as a simple explanation :
For the first case :
for (var x = 0; x < 6; x +=2){}
console.log(x);
// output : 6
So, at the very first time x is 0
Then at the second attempt x is increased by 2 ! That means 0 + 2 = 2!
3rd attempt 2 + 2 = 4 !
4th attempt => 4 + 2 = 6
Now x has been 6 and our condition is untill x < 6 we will increase it by 2! Now 6 is not less than 6! So the loop will stop! And that's how the output is 6!
For the second case :
for (var x = 1; x < 6; x +=2){}
console.log(x);
// output : 7
1st attempt => 1 + 2 = 3
2nd attempt => 3 + 2 = 5
The loop will run one more time! Cause 5 is less than 6! So,
Last attempt => 5 + 2 = 7
And that's why the output is 7!
And the 3rd case is as same as above 😇
You will get an error if you use 'let' instead of using 'var' ! Try doing that 😁
+ 7
ThanksitsQuasar✅ &Diego
It was so simple but.......
Thanks and love you both😍😊
+ 7
ThanksArb Rahim Badsa
&
Thanks(Basel Al_hajeri)('MBH')
+ 4
Of course, in the middle is increments before the condition
+ 3
Tahir Usman after every loops the complier runs other one just .
1.the last one in loop is 4 after loop 6
2.the last one in loop is 5 after loop 7
3.the ....in loop is 4 after it 6
As usual 🙂
+ 3
As Arb Rahim Badsa said
I've made it a simple to make u understanding
+ 2
for(x=0;x<6;x+=2){}
Console.log(x);
means:
1. 2+2=4
2. 4+2=6
3. 6=6 => nothing
+ 2
for(x=1;x<6;x+=2){}
Values "x" takes are 1, 3, 5 , 7 (not less than 6 so loop stops).
for(x=0;x=6;x+=2){}
Values "x" takes are 0, 2, 4, 6 (not less than 6 so loop stops).
+ 1
see the code here
https://code.sololearn.com/Wx7X5qNhdx2x/#js