0
0
JavascriptHow-ToBeginner · 3 min read

How to Create Infinite Loop in JavaScript: Syntax and Examples

To create an infinite loop in JavaScript, use a while(true) or for(;;) loop which runs endlessly until stopped. These loops keep executing the code inside them without a stopping condition.
📐

Syntax

An infinite loop runs forever because its condition never becomes false. Common syntax patterns include:

  • while(true) { ... }: The condition true never changes, so the loop never ends.
  • for(;;) { ... }: No initialization, condition, or increment means the loop runs endlessly.
javascript
while (true) {
  // code to repeat forever
}

// or

for (;;) {
  // code to repeat forever
}
💻

Example

This example shows an infinite loop that prints a message repeatedly. It uses while(true) to keep running.

javascript
let count = 0;
while (true) {
  console.log('Loop iteration:', count);
  count++;
  if (count >= 5) {
    break; // stops the infinite loop after 5 iterations
  }
}
Output
Loop iteration: 0 Loop iteration: 1 Loop iteration: 2 Loop iteration: 3 Loop iteration: 4
⚠️

Common Pitfalls

Infinite loops can freeze your program or browser if not handled carefully. Common mistakes include:

  • Forgetting a break or exit condition to stop the loop.
  • Using infinite loops without asynchronous pauses, causing the program to hang.
  • Writing loops that never update variables controlling the loop condition.

Always ensure you have a way to exit or pause an infinite loop.

javascript
/* Wrong: Infinite loop without exit */
// while(true) {
//   console.log('This will run forever and freeze your program');
// }

/* Right: Using break to stop loop */
let i = 0;
while (true) {
  console.log(i);
  i++;
  if (i === 3) {
    break;
  }
}
Output
0 1 2
📊

Quick Reference

Remember these quick tips for infinite loops in JavaScript:

  • Use while(true) or for(;;) for infinite loops.
  • Always include a break or exit condition to avoid freezing.
  • Use infinite loops carefully, especially in browsers.

Key Takeaways

Use while(true) or for(;;) to create infinite loops in JavaScript.
Always include a way to exit the loop, like a break statement, to prevent freezing.
Infinite loops without pauses can hang your program or browser.
Test infinite loops carefully and avoid running them without control.
Use infinite loops only when you need continuous repetition until a condition is met.