Infinite Loop

In a while loop, you need to write a condition for the loop to continue to run. However, if you don't handle the condition correctly, it's possible to create an infinite loop. Look at this example, which tries to print out the numbers 0 to 9:

let i = 0;
while (i < 10) {
    console.log(i);
}

But there is a bug here! There is no i++ at the end of the loop body, so i will never increase. This means that i < 10 will always be true and the loop will never end. This is called an infinite loop, which can cause your program to freeze. Be cautious when using a while loop!

break out of a loop

Having the condition which is always true in your while loop isn't necessarily bad in some situations. Sometimes these loops can simplify program logic and make it easier to understand, but in order for it to not overload your computer, you must have another way for the program to exit the loop. Let's write a program that repeatedly accepts integers from user input and print out the squares, until the input is 0. Here is the logic in plain English:

~ Start an infinite loop.
~ Get user input.
~ If input is 0, stop the loop.
~ If input is not 0, do math and continue the loop.

This kind of while loop is infinite:

while (true) {
  ...
}

break keyword

In the above loop, the condition itself is true, so the computer will always continue running the loop. Now we need a way to exit the loop. This can be done with break keyword. break will cause the current loop to end, and the computer will jump to the code directly following the loop. Here is a good example of an infinite loop that works:

while (true) {
    let n = Number(prompt('Give me an integer: '));

    if (n == 0) {
      break;
    }

    console.log(n + ' * ' + n + ' = ' + (n*n));
}

console.log('done');

Enter 5, 9, 6, 0 Sample output:

5*5=25
9*9=81
6*6=36
done

In this example, the computer will continue running the code until the user gives it an input of 0.

If you have nested loops (loop inside another loop), break only exits one layer of the loop, and the code continues in the outer loop. It's possible to break out of nested loops using a label reference:

break label;

But we will not cover that topic in this book.

results matching ""

    No results matching ""