Skip to content
Advertisement

Why doesn’t the for loop stop on les then operator (<) but continues to loop one more time to be (=) to 5

The operator is les then or equal. So why does it continue to loop one more time since when it looped 4 times, it reached one of it’s conditions?

for (let i = 0; i <= 5; i++) {
  console.log(i);
  console.log("Hello World!");
}

Advertisement

Answer

You are correct that <= means less than or equal, but I believe you are confusing how loops work. The second statement in a for-loop declaration is called the condition, and defines when a loop can continue to execute. If the condition returns true, the loop body is executed. If false, it breaks.

If it helps, you can imagine it as a while loop where

for(declaration; condition; increment) 
{
    //loop body
}

is fundamentally equivalent to

declaration;
while(condition)
{
    //loop body
    increment;
}

A condition of i <= 5 means the loop will continue to execute as long as the i is less than or equal to 5. It does not mean the loop will break if i is no longer both less than nor equal to 5.

The simple change is to use i < 5.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement