Loops and switch

  1. The while and do..while loops
  2. The for loop
  3. Jumping out with break
  4. Skipping with continue
  5. Jumping over blocks with labels
  6. The switch construct
    1. Example
    2. User-input example

Loop constructs allow to repeat a block of code multiple times, while the given condition is true.

JavaScript has three types of loops.

The while and do..while loops

These loops check condition before/after every iteration:

while(i<10) {
  // do something
}

do {
  // something
} while (i<10)

The code inside curly braces will repeat while the condition (i<10 in the example) holds true.

An endless loop looks like:

while(true) {
  // do something
}

As with many other languages, you check for 0 like this:

var i = 3
while(i) {
  alert(i--)
}

The loop above will stop when i==0, because 0 is false in boolean context.

Note that i-- decrements i, but returns a value before decrement. That’s why alert starts with 3 and ends with 1.

The for loop

This loop looks like:

for(i=0;i<10;i++) {
  alert(i)
}

The statement consists of three parts divided by semicolon and the body.

Here is a description of the parts (generally same as in C, Java, PHP etc):

i=0 - starter
This executes at loop start.
i<10 - loop condition
The condition to check if loop is finished. It is checked after every execution of loop body.
i++ - increment
An action to perform after every iteration, but before the loop condition is checked.

For the given example, the loop body is executed with i starting from 0 to 9. When i++ makes i=10, the loop is stopped by condition i<10.

It is a common practice to define a loop variable inside for:

for(*!*var*/!* i=0; i<10; i++) { ... }

You can leave any part of for empty. For example, a simple infinite loop looks like:

for(;;) { 
  // will repeat eternally (in theory)
}

Check out the page: tutorial/intro/source/loop.html.

The task is to rewrite for loop into while with same code behavior.

Open solution
Solution

The solution is represented by the source code here.


Create a loop that keeps prompting for a number exceeding 100. When a user types in a number>100, the loops must stop.

Pressing “ESC” or clicking “Cancel” must stop the loop also.

Check how it should work here.

Open solution
Solution
Check source for the solution: [play src="tutorial/intro/endless_loop.html"].

Jumping out with break

Sometimes it is required to break out of the loop right now. This is what break statement does.

The following loop will exit from loop when i becomes 6.

The execution will continue from right after the loop (marked with asterisk).

var i=0
while(true) {

  i++   // increase i by one

  *!*if (i>5) break*/!*

  alert(i)
}
// (*)

Skipping with continue

The continue operator allows to skip the rest of the block.

For example, the following code ignores negative values:

var i = -3
while(i<3) {

  i++
  
  *!*if (i<0) continue*/!*

  alert(i)  // (*)
}

The code labelled with asterisk is never executed for negative i, thanks to continue.

Jumping over blocks with labels

Loop labels is something special in JavaScript.

They are used to break/continue through several nested loops.

A label is put before loop statement, and can be put on a separate line:

*!*outer:*/!* 
for(;;) {
  // ...
  *!*inner:*/!* for(;;) {
    // ...
  }
}

One can use break label and continue label to jump through several loops.

The following example demonstrates how to break through two loop levels.

outer: 
for(;;) {
  
  for(i=0; i<10; i++) {

    if (i > 3) break outer;

  }

  // the part of code after inner loop is never executed, 
  // because break jumps right to outer label
  
}
alert("i="+i);

You can use continue in exactly the same way. It will jump to next iteration of labelled loop.

An interesting thing about labels is that you can attach them to blocks:

my: {

  for(;;) {
    for(i=0; i<10; i++) {
      if (i>4) break my;
    }
  }
  
  some_code;

}
alert("after my");

In the given example, break jumps over some_code, to the end of the block labelled with my.

That looks like goto, but it is not, because you can’t break outside loops, and you also can’t break to a place of code before.

JavaScript has no goto. Even in latest editions of the standard.

A number is prime if it has exactly two divisors: 1 and itself.
Or, in other words, n>1 is prime if numbers 2..n-1 all divide n with a non-zero remainder.

Create a code which outputs all primes less than 10. There should be 2,3,5,7.

P.S. The code should also work if 100, 1000, any other value in place of 10.

Open hint 1
Hint 1
Open solution
Solution

The solution:

next_prime: 
for(var i=2; i<10; i++) {

  for(var j=2; j<i; j++) {
    if ( i % j == 0) continue next_prime
  }
  
  alert(i)  // prime
}

The switch construct

Another useful construct in JavaScript is switch. It provides a short syntax for multiple equality tests.

It looks like this:

switch(x) {
  case 'value1':  // if (x === 'value1')
    ...
  case 'value2':  // if (x === 'value2')
    ...
  default:       
    // default code
}

Switch operator checks the argument against each case and executes the code below the match until it meets the break operator.

If no case matches, it goes to optional default label.

Example

Let’s see a working example.

var x = 2

switch(x) {
  case 1:
    alert('never executes')
 
  case 2:   
    alert('x === 2')  
 
  case 3:
    alert('x === 3')
}

The example above outputs 2 and 3. That’s because it starts execution from case 2 and goes on.

To stop the execution of a case, we need to add break:

var x = 2

switch(x) {
  case 1:
    alert('never executes')
    break

  case 2:   
    alert('x === 2')   // <-- start
    break              // stop!

  case 3:
    alert('x === 3')
    break
}

In the example above, every case is appended by break. That is a usual practice to ensure that only one case is executed.

User-input example

The next example is based on user-input.

var arg = prompt("Enter arg?")
switch(arg) {
  case '0':
  case '1':
    alert('One or zero')

  case '2':
    alert('Two')
    break

  case 3:
    alert('Never happens')

  case false: 
    alert('False')
    break

  default:
    alert('Unknown value: '+arg)
}

  • If you enter 0 or 1 it starts execution from the corresponding case, executes the first alert, then the second one and stops at break.
  • If you enter 2, switch goes right to case 2, skipping first alert.
  • If you type in 3, switch goes to default case. That’s because prompt returns string '3', not number. Switch uses === to check equality, so case 3 will not match.

That’s also the reason why case false also never works in this example. It would work if arg === false, but prompt returns either a string or null.

Tutorial

Donate

Donate to this project