Reliable and Recognized JavaScript Certification Online #

Jumps are control structures that cause a jump to another part of the program.

break

The break statement causes an immediate exit from a loop (while, do-while, for, for-in, for-of) or switch. It has the following syntax:

break [label];

If the break statement is used without a label, it exits from the current loop or switch.
If the break is used with a label it terminates the specified labeled statement.

An example:

var collection = ['x', 'y', 3, 5, 'a'];
var containsNumber = false;
for (i = 0; i < collection.length; i++) {
    if (!isNaN(collection[i])) {
        containsNumber = true;
        console.log('The number found: ' + collection[i]);
        break;
    }
}</pre>
// Output:
// The number found: 3

In the above example, it is checked if the collection contains any number. If so, the first number found is displayed and the loop exits.

 

continue

The continue statement stops the current iteration of loop and begins to execute the next iteration of the loop. It has the following syntax:

continue [label];

The continue statement used without label terminates the current iteration of immediately enclosing loop. Whereas using continue with a label inside nested loops it terminates the current iteration of loop identified with that label.

An example

for (var i = 1; i <= 10; i++) {
    if (i % 2 === 0) {
        continue;
    }
    console.log(i);
}

In the example above, even numbers are skipped and only the odd numbers are displayed.

 

labeled statement

The labeled statement provides an identifier for a statement that you can use to refer to it elsewhere in the program.

The syntax is as follow:

label:
statement

The break and continue statements are the only statements that use labels to specify the statement to which they apply.

An example:

var i, j;

outerLoop:
for (i = 0; i < 3; i++) {
    j = 0;
    while(j < 3) {
        if (i === 1 && j === 1) {
            continue outerLoop;
        }
        console.log('i = ' + i + ', j= ' + j);
        j++;
    }
}
// Output:
// i = 0, j= 0
// i = 0, j= 1
// i = 0, j= 2
// i = 1, j= 0
// i = 2, j= 0
// i = 2, j= 1
// i = 2, j= 2

Using continue with the outerLoop label, two pairs of values have been skipped.

No Comments

Reply