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👋!

Latest comments (0)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another “Coder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.