What is an infinite loop?

QuestionsQuestions8 SkillsProDec, 12 2025
0172

That's a very important concept in programming!

An infinite loop is a sequence of instructions that, as its name suggests, loops endlessly or indefinitely, because the terminating condition is never satisfied. This means a program gets stuck in that loop and never moves on to execute the code that comes after it.

It usually happens when:

  1. The loop condition is always true: For example, in a while loop, if the condition always evaluates to true, the loop will never stop.
    let x = 1;
    while (x > 0) { // x will always be > 0, so this loop never ends!
      console.log("Stuck in an infinite loop!");
    }
  2. The counter or condition variable is not updated correctly: In a for loop or a while loop, if you forget to increment (or decrement) the counter, or if the condition that would eventually make the loop stop is never met, it becomes infinite.
    // Example from our discussion earlier, if we forget i++
    let i = 1;
    while (i <= 5) {
      console.log("Current count: " + i);
      // i++; <--- If this line is missing, 'i' remains 1 forever!
    }
    In this case, i would always be 1, so i <= 5 would always be true, leading to an infinite loop.

When a program enters an infinite loop, it typically consumes a lot of CPU resources, and the program will appear to "freeze" or become unresponsive. In web browsers, an infinite loop in JavaScript can make the tab unresponsive or even crash it.

It's a common mistake for beginners, but understanding why they happen helps you avoid them!

0 Comments

no data
Be the first to share your comment!