Hello there folks, back again to bother you with a dumb question, hope you dont mind
so take a look at this bit of code :
/* //this doesnt work.
//why ?
for (let i = 0; i == 10; i+= 1){
console.log(i);
}
*/
//this works
for (let i = 0; i <= 100; i+= 1){
console.log(i);
if (i === 10){
break;
}
}
Why does the first version not display anything on the log nor does it call for an error ?
After some testing it seems to be the second argument of the For loop it seems to not accept my comparator : i == 10 or i === 10;
No idea why though.
Thanks in advance.
In your first loop, you have initialized the loop variable i as 0.
Before the first iteration of the loop, the loop condition i == 10 is evaluated. Since 0 is not equal to 10, so the condition is false. Therefore, we exit the loop immediately.
Contrast this with the loop,
for (let i = 0; i != 10; i+= 1){
console.log(i);
}
// This will print numbers 0 through 9 on separate lines.
In this loop, the loop condition evaluates to true and consequently the loop body is executed. Once the loop condition becomes false (when i equals 10), the loop ends.
Alright, gotcha thanks mtrtmk it all makes sense now.
Really appriciate the inequality exemple, always wondered why,when to use it.
We killed two birds with one stone, with this one.