DEV Community

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

Posted on

3 2

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đź‘‹!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay