Continue the loop in JavaScript


With the continue statement we can stop the current iteration of the loop, and continue with the next.

When JavaScript hits continue, it skips (not execute) any code left, and jumps directly to the next iteration instead.

In this example, we will not let anyone inside a bar if their age is less than 21:

let ages = [10, 30, 21, 19, 25];

for (let age of ages) {
	if (age < 21) {
		continue;
	}
	console.log(`Someone of age ${age} entered the bar.`);
}

The output of this program is:

Someone of age 30 entered the bar.
Someone of age 21 entered the bar.
Someone of age 25 entered the bar.

As you can see, our program doesn't print for ages 10 and 19.

Here's what happens during this loop:

1. First iteration:
	a. age = 10
	b. Is age < 21? Yes:
	    continue => Go directly to the next age
	
2. Second iteration:
	a. age = 30
	b. Is age < 21? No.
	c. console.log
	
3. Third iteration:
	a. age = 21
	b. Is age < 21? No.
	c. console.log

4. Forth iteration:
	a. age = 19
	b. Is age < 21? Yes:
	    continue => Go directly to the next age
      
5. Fifth iteration:
	a. age = 25
	b. Is age < 21? No.
	c. console.log

Assignment
Let's allow only the people with height at least 170 into the arena.


Hint
Look at the examples above if you get stuck.


Introduction

The continue statement in JavaScript is a powerful tool for controlling the flow of loops. It allows you to skip the current iteration and proceed directly to the next one. This can be particularly useful in scenarios where you want to filter out certain elements or conditions within a loop. Understanding how to use continue effectively can help you write cleaner and more efficient code.

Understanding the Basics

The fundamental concept of the continue statement is straightforward: it stops the current iteration of a loop and moves to the next iteration. This is different from the break statement, which exits the loop entirely. Here's a simple example to illustrate:

for (let i = 0; i < 5; i++) {
    if (i === 2) {
        continue; // Skip the iteration when i is 2
    }
    console.log(i);
}
// Output: 0, 1, 3, 4

In this example, when i is 2, the continue statement skips the rest of the loop body and proceeds to the next iteration.

Main Concepts

To apply the continue statement effectively, you need to understand the logical flow of your loop and the conditions under which you want to skip iterations. Let's break down the example provided in the lesson:

let ages = [10, 30, 21, 19, 25];

for (let age of ages) {
    if (age < 21) {
        continue; // Skip the iteration if age is less than 21
    }
    console.log(`Someone of age ${age} entered the bar.`);
}

Here, the loop iterates over an array of ages. If the age is less than 21, the continue statement skips the rest of the loop body and moves to the next age. This ensures that only ages 21 and above are logged.

Examples and Use Cases

Let's consider another example where we only allow people with a height of at least 170 cm into an arena:

let heights = [160, 172, 168, 180, 175];

for (let height of heights) {
    if (height < 170) {
        continue; // Skip the iteration if height is less than 170
    }
    console.log(`Someone with height ${height} entered the arena.`);
}
// Output:
// Someone with height 172 entered the arena.
// Someone with height 180 entered the arena.
// Someone with height 175 entered the arena.

In this example, the loop iterates over an array of heights. If the height is less than 170, the continue statement skips the rest of the loop body and moves to the next height. This ensures that only heights 170 and above are logged.

Common Pitfalls and Best Practices

One common mistake when using the continue statement is forgetting to include the condition that triggers it. This can lead to unexpected behavior in your loops. Here are some best practices:

Advanced Techniques

In more complex scenarios, you might need to use continue within nested loops. Here's an example:

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

for (let row of matrix) {
    for (let num of row) {
        if (num % 2 === 0) {
            continue; // Skip even numbers
        }
        console.log(num);
    }
}
// Output: 1, 3, 5, 7, 9

In this example, the inner loop skips even numbers and only logs odd numbers.

Code Implementation

Let's implement the assignment where we allow only people with a height of at least 170 cm into the arena:

let heights = [160, 172, 168, 180, 175];

for (let height of heights) {
    if (height < 170) {
        continue; // Skip the iteration if height is less than 170
    }
    console.log(`Someone with height ${height} entered the arena.`);
}

This code iterates over an array of heights and uses the continue statement to skip heights less than 170 cm.

Debugging and Testing

When debugging code that uses the continue statement, it's important to check the conditions that trigger it. You can use console logs to verify the flow of your loop:

let heights = [160, 172, 168, 180, 175];

for (let height of heights) {
    if (height < 170) {
        console.log(`Skipping height ${height}`);
        continue; // Skip the iteration if height is less than 170
    }
    console.log(`Someone with height ${height} entered the arena.`);
}

Writing tests for functions that use continue can help ensure your logic is correct. Here's an example using a simple test case:

function filterHeights(heights) {
    let allowedHeights = [];
    for (let height of heights) {
        if (height < 170) {
            continue; // Skip the iteration if height is less than 170
        }
        allowedHeights.push(height);
    }
    return allowedHeights;
}

// Test case
console.log(filterHeights([160, 172, 168, 180, 175])); // Output: [172, 180, 175]

Thinking and Problem-Solving Tips

When approaching problems that might require the continue statement, consider the following strategies:

Conclusion

The continue statement is a valuable tool for controlling loop iterations in JavaScript. By understanding its usage and applying it effectively, you can write cleaner and more efficient code. Remember to practice and explore different scenarios to master this concept.

Additional Resources