4.6 Infinite Loops
When you write loops, you should know what we call an infinite loop. An infinite loop, as the name suggests, runs forever. So if you accidentally create one of these loops, you will crash your browser or your computer. Let me show you an example. So here, I'm going to declare a variable, and set it to 0, I'm going to put it in a while loop, so as long as i is less than 5, we're going to do a console. log, of i, here technically, we have to increment i, but if you forget to do that, you end up creating an infinite loop, because in the first iteration, i is equal to 0. And it's less than 5, so we'll display an i on the console. Now, in the second iteration, i is still equal to 0 and less than 5. So this loop could go on forever. So I'm going to save the changes, now on the console, this number that you see before 0 is the number of times you display 0 on the console, so you can see that number is increasing rapidly. And if you look at the browser, you can see that the page loads infinitely. So the only way to get rid of it is to close that window, or if that doesn't work, you'll have to force it to close. So here is 1 example of an infinite loop. Here's another example Let's do a while true. Again, this loop will go on forever. So it's an infinite loop. And by the way, infinite loops are not limited to while loops, we can create an infinite do while loop, so we do a do while (true) ,similar to the last example, we might create a loop variable like 0 and then have a condition like x less than 5, but we forget to increment x here. We can also create an infinite for loop. So, for i to be 0, as long as i is greater than 0, i ++, again with the condition we placed here, this loop will work forever, or maybe we have the right condition, like if i is less than 10, but we forget to add the third part So, we don't increment i, and it's exactly like this while loop we had earlier without incrementing i. So be aware of infinite loops, avoid them, because they can crash your browser or your computer. That's it for this little demonstration on infinite loops, we'll meet again for a next video on For...In loops