Why does using a condition like 'i = 5' in a 'for' loop cause an infinite loop?

Sorry if I muck up the formatting here, still getting used to it.

Let’s say I have the following:

for (let i = 0; i = 5; i++) {

  console.log(i);

}

This will just keep logging 5 over and over.

Why is this? My understanding is that:

  • let i = 0 sets the counter
  • i = 5 sets the exit condition. If it evaluates to false then the code will not execute
  • i++ sets the action to take at the end of the loop

Shouldn’t the code in the loops just not execute because i = 5 is false at the start?

Even if it does execute, shouldn’t i increment after each loop? How does it just get stuck on 5?

This uses the assignment operator,=, not the comparison operator ===.

(i = 5) != (i == 5) != (i === 5)

1 Like

oh my god

Can you tell I’m new to this? :smiling_face_with_tear:

Well don’t I feel silly

It happens. We’ve all made that mistake :slight_smile:

1 Like

Everyone has made that mistake at least a few times.

2 Likes

It is so common that some languages have (rightly so I’d say) changed either the assignment or comparison operators. Some languages have operator keywords as well like for example “and”, “or”, “not”, etc. to help with legibility.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.