Javascript repetition

There are many situations where you will want the program to run in a loop and repeat the same series of commands over and over again. These break down into two broad categories; either you know beforehand how many times that the loop is going to run or you don't know the exact number of times.

  • Use the for loop when you want to run for a fixed number of loops.
  • Use the while loop when you want to run as long as something remains true.

break and continue

You can use the break and continue keywords to override the behaviour of any type of Javascript loop.

Use the break keyword if you need to be able to jump out of the loop before the controlling condition has been satisfied. Typically this will be done inside an if statement so that the loop will terminate early if some particular condition is met. As an example, this while loops asks the user to enter a password and will keep on asking until the user types in the right value - "secret". Overridding this though is an if that will display a warning message and use break to abandon the loop once three attempts have been made.

var pwd = "";
var tries = 0;
while (pwd !="secret")
  tries = tries + 1;
  if(tries > 3)
    alert("Too many attempts");
  pwd = prompt("Enter the password...");

The continue keyword also interrupts the normal flow of the loop but instead of stopping the loop completely like break, it just abandons the current pass and evaluates the controlling condition once again.