Why inside the loop the greatest value of i is 7 but the outside it prints 8 any explanation please?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Why inside the loop the greatest value of i is 7 but the outside it prints 8 any explanation please??

https://code.sololearn.com/WNBQw7mIjhtm/?ref=app

17th Mar 2019, 6:50 PM
Hafsa Mohamed
Hafsa Mohamed - avatar
5 Answers
+ 4
The break condition in the for loop is i < 8. When i is equal to 7, it will still meet this i < 8 condition and be the final console.log() execution from within the loop. When i is incremented (i ++) after this, and i is equal to 8, it will not execute the console.log(i) statement as 8 < 8 is not true (you can use less than or equal to if you want: i <= 8 ) The console.log() statement outside the for loop is then executed with i = 8
17th Mar 2019, 7:09 PM
Jenine
+ 8
for(var i=4;i<8;i++) { console .log(i); //expected ouput:4,5,6,7 } //outside the loop console .log ("outside the loop: "+i); //expected output:8 1. i = 4 ; 4 < 8 it is true will print 4 ; after that will add 1 to 4 . 2. i = 5; 5 < 8 it is true will print 5; after that will add 1 to the 5. 3. i = 6 ; 6 < 8 it is true so will print 6; after that will add 1 to 6. 4. i = 7; 7 < 8 it is true so will print 7; after that will add 1 to 7. 5. i = 8; 8 < 8 it is false will stop execute, note : out side the condition value i = 8. i wish this will help you so do not forget to Vote :)
19th Mar 2019, 8:32 AM
Khalid Issa Talaf Ibrahim
Khalid Issa Talaf Ibrahim - avatar
+ 6
i am glad it is help , welcome :)
19th Mar 2019, 8:01 PM
Khalid Issa Talaf Ibrahim
Khalid Issa Talaf Ibrahim - avatar
+ 3
Thank you very much it is helpful answer
19th Mar 2019, 8:43 AM
Hafsa Mohamed
Hafsa Mohamed - avatar
+ 2
The variables declared with "var" don't have a block scope. That's why they are accessible out of the loop. You can find more info here: https://www.w3schools.com/js/js_let.asp
17th Mar 2019, 7:05 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar