When working with while and for loops in JavaScript sometimes you can easily create infinite loops without knowing it. These types of loops will not terminate and will run indefinitely which will make your program unresponsive and will utilize your CPU to the max.

What is an infinite loop in JavaScript?

Loops in programming are fundamental code structures that allow you to execute a specific block of code repeatedly until a certain condition is met. It's a way to automate repetitive tasks and iterate over a collection of elements. However, if that certain condition is not met, the loop will run indefinitely, which will result in an infinite loop, which if not made intentionally is generally a bad thing. 

Here is an example of an infinite loop in JavaScript

while(true) {
  console.log('Hello, how are you? ');
}

The following code will output Hello, how are you? Hello, how are you? Hello, how are you?... indefinitely.

Other examples of infinite loops are

// Empty for loop which is essentially like while(true) loop
for(;;) {
  console.log('Infinity');
}

// This is also an infinite loop because the condition will always be true 
// the variable i will always be less than 100 because we decrement the 
// value on each iteration, if we increment it, then the loop will be finite.
for(let i = 0; i<= 100; i--) {
  console.log('infinity');
}

How to prevent infinite loops in JavaScript?

To prevent infinite loops in JavaScript you need to ensure that your loop's condition can eventually become false, so the loop can terminate.

Here are some common practices to avoid infinite loops:

  1. Updating loop variables: Make sure the loop variable or condition is being updated inside the loop, so the loop can eventually reach a termination condition.
    let i = 0;
    while (i < 5) {
      console.log(i);
      i += 1
    }
  2. Using a break statement: Inside the loop, you can use a conditional statement along with the break keyword to exit the loop when a specific condition is met.
    let i = 0;
    while(true) {
      i += 1
      if (i == 5) {
        break;
      }
    }

    This loop will execute 5 times and the it will break because of the if (i == 5) check

By being mindful of loop conditions and controlling the loop flow properly, you can avoid unintentional infinite loops and ensure your programs run smoothly and efficiently.

Additional resources