Home > Blockchain >  Don't understand why my for loop code isn't working
Don't understand why my for loop code isn't working

Time:01-05

I was playing with the break and continue keyword but I notice in chrome console this code doesn't work

     for (let i = 0; i > 5; i  ) {
     console.log(i);
     } //this will print all number from 1 to 5 but console showing undefined

However I tried changing i = 5 or i === 5 still it doesn't work

But when I changed it to i < 5 then it yields correct result.

Why is that?

CodePudding user response:

your condition is i > 5. At the beginning i = 0 so it will not run ever. put i < 5

CodePudding user response:

Please check following diagram

diagram

Condition getting false on the first time so code block won't execute

CodePudding user response:

i<5 indicates that the for loop will run as long as i is less than 5. i>5 indicates that 0 is less than 5 (let i = 0). So the correct program should be -

for (let i = 0; i <= 5; i  ) {
     console.log(i);
} 

  •  Tags:  
  • Related