Infinite Loops

Infinite loops are loops that run forever because the boolean condition never returns false. Here is an example of an infinite loop (if you run this in your browser, the browser might freeze, and you might have to quit your session):

while (5 === 5) {
  console.log("this never ends");
}

The boolean condition always returns true (5 === 5), so this loop will run forever.

Compare the infinite loop to a loop that will terminate:

var x = 0;
while (x < 3) {
  console.log("this ends!");
  x++;
}

In this loop, the counter variable (x) will eventually be greater than 3, so the loop will terminate.

If we forget to increment the counter variable, we will create an infinite loop. Here is another example of an infinite loop:

var x = 0;
while (x < 3) {
  console.log("on and on");
}

The counter variable x is never incremented (note the absence of an x++). The variable x remains assigned to 0, never reaching 3. That means the condition x<3 will keep returning true every time we loop. This loop will continue forever.

Question Click to View Answer

Is the following loop an infinite loop? Explain why/why not.

x = 4;
while (x === 4) {
  console.log("will I terminate?");
}

This is an infinite loop because the boolean condidion (4 === 4) always evaluates to true.

Is the following loop an infinite loop? Explain why/why not.

var counter = 0;
while (counter < 4) {
  console.log("give me chicken");
}

The counter variable is assigned to 0 and is never reassigned, so the boolean condition (0 < 4) always evaluates to true. The loop continues forever.

Is the following loop an infinite loop? Explain why/why not.

var counter = 0;
var i = 0;
while (counter < 100) {
  console.log("I like Indian food");
  i++;
}

Yes, this is an infinite loop.

The i variable is incremented for each loop iteration, but the counter variable is unchanged, so the boolean condition is always true. The loop iterates forever.

<-- Previous (While Loops) Next (While Loops With Arrays) -->