Start learning free

LESSON 185 OF 675 · LOOPING OVER ARRAY INDICES

Continue the loop in TypeScript

Lesson

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 executing) 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. Fourth 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