+ 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

12th May 2019, 8:17 PM
Tahir Usman
Tahir Usman - avatar
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 😁
12th May 2019, 9:56 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 7
ThanksitsQuasar✅ &Diego It was so simple but....... Thanks and love you both😍😊
12th May 2019, 8:37 PM
Tahir Usman
Tahir Usman - avatar
12th May 2019, 11:31 PM
Tahir Usman
Tahir Usman - avatar
+ 4
Of course, in the middle is increments before the condition
14th May 2019, 1:07 AM
Oliver Valiente Oliva
Oliver Valiente Oliva - avatar
+ 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 🙂
12th May 2019, 9:26 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
+ 3
As Arb Rahim Badsa said I've made it a simple to make u understanding
12th May 2019, 10:29 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
+ 2
for(x=0;x<6;x+=2){} Console.log(x); means: 1. 2+2=4 2. 4+2=6 3. 6=6 => nothing
12th May 2019, 8:24 PM
itsQuasar✅
itsQuasar✅ - avatar
+ 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).
12th May 2019, 8:30 PM
Diego
Diego - avatar
13th May 2019, 10:12 PM
Thomas Wittek
Thomas Wittek - avatar