Start learning free

LESSON 152 OF 348 · LOOPING OVER ARRAY INDICES

Continue in For Loops in TypeScript: Skipping an Iteration

Lesson Read the full explanation

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

When TypeScript 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.


STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · LOOPING OVER ARRAY INDICES

    Continue In For Loops in TypeScript, explained

    What continue does

    The continue statement ends the current iteration of a loop and jumps straight to the next one. Any statements after continue in the loop body are skipped for that element, but the loop itself keeps running. This differs from break, which ends the loop entirely.

    It is useful when some elements should be ignored and the rest need the same handling. Instead of wrapping the main work in a large if, you filter out the unwanted elements at the top of the loop and leave the main work at the normal indentation level.

    An example: a bar with an age limit

    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 is:

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

    Here is what happens in each iteration:

    • age = 10: the test age < 21 is true, so continue jumps to the next element and nothing is printed.
    • age = 30: the test is false, so the program prints.
    • age = 21: the test is false because 21 is not less than 21, so the program prints.
    • age = 19: skipped, like the first one.
    • age = 25: printed.

    The line with console.log uses a template literal: text between backticks, with ${...} inserting a value.

    The lesson's exercise

    The starting code has an array of heights:

    let heights: number[] = [180, 139, 174, 190, 162];
    

    Only people at least 170 tall are allowed into the arena, so only those heights should be printed. The steps:

    1. Write the loop. Use for (let height of heights). The variable must be called height, and for...of gives the values, not the positions.
    2. Skip the short ones. Inside the loop, test height < 170 and call continue when it is true. Anyone below the limit is skipped before reaching the print.
    3. Print the rest. Below the if, write console.log(height). This line is only reached by heights of at least 170.

    The full program:

    let heights: number[] = [180, 139, 174, 190, 162];
    
    for (let height of heights) {
        if (height < 170) {
            continue;
        }
        console.log(height);
    }
    

    It prints:

    180
    174
    190
    

    Notice that the condition describes who to skip (< 170), the opposite of the requirement (at least 170). Writing the test for the people you want to reject is what makes continue read naturally. The same output also comes from the opposite style, if (height >= 170) { console.log(height); }, which has no continue. That form is perfectly fine for one condition, and continue pays off when there are several checks or a long body.

    Details and gotchas

    • The boundary value. The test is height < 170, not <= 170. A person exactly 170 tall must be let in, and <= would skip them.
    • Order matters. Code written before continue in the body still runs for every element. Put the print after the check, as here, or the skipped heights get printed too.
    • In a for loop, the step still runs. With for (let i = 0; i < n; i++), continue jumps to the i++ part and then tests the condition, so the loop always makes progress.
    • Danger in while loops. A while loop has no step in its header. If the counter is updated at the bottom of the body, a continue placed above it skips the update, and the loop may never end. Update the counter before the continue.
    • Only the innermost loop. In nested loops, continue applies to the loop it is written in. A label before the outer loop lets you write continue followed by that label to move on the outer loop.
    • Not in forEach. The body of a forEach callback is a function, so continue is not allowed there. A return inside the callback has the same effect of skipping one element.

    An index-based version

    The same idea works with indices, which you use when you need the position as well as the value:

    for (let i = 0; i < 6; i++) {
        if (i % 2 == 0) continue;
        console.log(i);
    }
    

    This prints 1, 3 and 5, the odd numbers below 6, because every even i is skipped.

    Key takeaways

    • continue skips the rest of the current iteration and starts the next one.
    • break leaves the loop, continue only skips one round.
    • Test for the elements you want to skip, then keep the main work after the check.
    • In a while loop, make sure the counter changes before any continue.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free