A loop that never ends is referred to as an “infinite” loop. In general, it is not a good practice to create an infinite loop with JavaScript because it could cause the program to freeze or crash. But, there are some scenarios where programmers need to run code continuously until a certain condition is satisfied or an external event takes place. In these cases, infinite loops are utilized. For instance, during game development, developers may need to design an infinite loop that continuously modifies the game’s state until it is finished.
This post will describe the method for creating infinite loops in JavaScript.
How to Create an Infinite Loop in JavaScript?
For creating an infinite loop in JavaScript, use the most common looping techniques including:
Approach 1: Infinite Loop Using “for” Loop
A JavaScript “for” loop is a control flow statement that permits to run a block of code repeatedly until a defined number of times. For an infinite loop, there are two ways, either set the end condition as “infinity” or not assign any end condition.
Syntax
For creating an infinite loop using the “for” loop:
// statement to be executed
}
Or use the given syntax for infinite loop:
// statement to be executed
}
Example
Set the “Infinity” as an end condition of the for loop to print the specified message infinitely:
console.log("I am an infinity loop");
}
The output displays the message infinite times:
Approach 2: Infinite Loop Using “while” Loop
“while” loop is also a JavaScript control flow statement that permits the execution of a code block repeatedly until a defined condition is “true”.
Syntax
The following syntax is utilized for creating an infinite loop using the “while” loop:
// statement to be executed
}
Example
Here, we will print the given message infinitely using the “while” loop to set the condition as “true”. This indicates that the loop will run infinitely:
console.log("I am an infinity loop");
}
Output
That’s all about creating an infinite loop in JavaScript.
Conclusion
To create an infinite loop in JavaScript, use the most common looping techniques including “for()” loop as “for (var i = 0; i < Infinity; i++) {}”, or “for (;;) {}”, and “while()” loop as “while (true) {}”. This post described the method for creating an infinite loop using JavaScript.