+ 4
Why inside the loop the greatest value of i is 7 but the outside it prints 8 any explanation please??
5 Réponses
+ 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
+ 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 :)
+ 6
i am glad it is help , welcome :)
+ 3
Thank you very much it is helpful answer
+ 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