DEV Community

Cover image for Infinite Loops in Javascript
Abhi Develops - SunTech
Abhi Develops - SunTech

Posted on

Infinite Loops in Javascript

Hi Everyone!
In this post I will be showing you what Infinite Loops are and how to avoid them while writing Javascript.

I have created many Javascript programs that include for or while loops and have messed up a lot. Most of the times I put the wrong operator in the loop which causes an Infinite Loop and my computer crashes.

I am going to show you an example of a for() infinite loop.

for (let i = 1; i >= 0; i++) {
    console.log(i)
}
Enter fullscreen mode Exit fullscreen mode

Just those 3 lines of code will make you have to restart your computer.

Here is another Infinite Loop example but it is a while() loop.

   const count = 1;
   while(count > 1) { 
       count++;
       console.log(count);
}
Enter fullscreen mode Exit fullscreen mode

Those lines of code can also crash your computer.

Do you want to know how to infinite loops?
The answer is: PUT THE CORRECT OPERATOR IN THE LOOP!!!

A Correct for() Loop:

for (let i = 1; i <= 0; i++) {
    console.log(i)
}
Enter fullscreen mode Exit fullscreen mode

A Correct while() Loop:

   const count = 1;
   while(count < 1) { 
       count++;
       console.log(count);
}
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed this post. Please remember to follow me for more posts.

Byeeeđź‘‹!

Top comments (0)