Chapter 4: Making Choices and Decisions

4.3 Jump Statements

We’ve now covered the main control flow statements available in Javascript. In this next section, we are going to look at some jump statements that are frequently used in control flow statements.

A jump statement is a statement that instructs the program to deviate from its normal flow sequence and jump to another line of code.

4.3.1 Break

The most commonly used jump statement is the break statement. We’ve already seen it at work when we discussed the switch statement. Let’s look at another example where it is used in a for loop.

When working with loops, you may want to exit the loop when a certain condition is met. You can do that with a break statement. To see how this works, try the example below:

var j = 0;
var i;

for (i = 0; i < 5; ++i) {
    j = j + 2;
    console.log('i = ' + i + ', j = ' + j);
    if (j === 6)
        break;
}

You should get the following output.

i = 0 , j = 2
i = 1 , j = 4
i = 2 , j = 6

Without the break statement, the program should loop from i = 0 to i = 4 because the test condition is i < 5. However, with the break statement, the program ends prematurely at i = 2. This is because when i = 2, j reaches the value of 6 and the break statement (on line 8) causes the loop to end.

In the example above, notice that we used an if statement within a for loop. It is very common for us to ‘mix-and-match’ various control tools in programming, such as using a while loop inside an if statement or using a for loop inside a while loop. This is known as a nested control statement.

4.3.2 Continue

Another useful keyword for loops is the continue keyword. When we use continue, the rest of the loop after the keyword is skipped for that iteration. An example will make this clearer.

var j = 0;
var i;

for (i = 0; i < 4; ++i) {
    j = j + 2;
    console.log('\ni = ' + i + ', j = ' + j);
    if (j === 6)
        continue;
    console.log("Everything from here is skipped when j = 6");
    console.log("Including this statement...");
    console.log("and this statement...");
}

You will get the following output:

i = 0, j = 2
Everything from here is skipped when j = 6
Including this statement…
and this statement…

i = 1, j = 4
Everything from here is skipped when j = 6
Including this statement…
and this statement…

i = 2, j = 6

i = 3, j = 8
Everything from here is skipped when j = 6
Including this statement…
and this statement…

When j = 6, the statements after the continue keyword are not displayed. Other than that, everything runs as per normal.