Search code examples
javascriptloopsfor-loopinfinite-loop

Javascript Infinite For Loop


I am learning for loops in javascript and trying some things I wrote the following basic code.

This code generates an infinite loop that only prints the number 4 indefinitely in the console.

The problem is that i don't understand the logic behind this and the exact reason why it happens

for(let i = 0; i = 4; i++){
   console.log(i);
}

Solution

  • In your loop, the condition part uses an assignment operator =, you should use a comparison operator such as !==. Note also that the condition should be false in order to exit the for loop. So !== it is (or <=, which I dislike for personal reasons), instead of ===.

    for(let i = 0; i !== 4; i++){
       console.log(i);
    }

    So your code runs indefinitely because i = 4 is truthy. And it prints 4 because i = 4 assigns 4 to i after increment