Start learning free

LESSON 151 OF 348 · LOOPING OVER ARRAY INDICES

Break in For Loops in TypeScript: Leaving a Loop Early

Lesson Read the full explanation

With the break statement, we can prematurely terminate a loop from inside that loop.

When TypeScript reaches the break statement, it's going to immediately terminate the loop without checking any conditions.


Breaking a for loop:

In this example, we will terminate the loop when we find a "banana" in our array:

let fruits = ["kivi", "orange", "banana", "apple", "pear"];
for (let fruit of fruits) {
	console.log(fruit);
	if(fruit == "banana") {
		break;
	}
}

The output of this code is:

kivi
orange
banana

As you can see, our program doesn't print apple and pear.

Here's what happens during this loop:

1. First iteration:
	a. fruit = "kivi"
	b. console.log(fruit) => Output: kivi
	c. Is fruit == "banana"? No.
	
2. Second iteration:
	a. fruit = "orange"
	b. console.log(fruit) => Output: orange
	c. Is fruit == "banana"? No.
	
3. Third iteration:
	a. fruit = "banana"
	b. console.log(fruit) => Output: banana
	c. Is fruit == "banana"? Yes:
          break => Exit the loop immediately

Here's the same program but iterating through the array with indices instead:

let fruits = ["kivi", "orange", "banana", "apple", "pear"];
for (let i = 0; i < fruits.length; i++) {
	console.log("Index " + i + ": " + fruits[i]);
	if(fruits[i] == "banana") {
		break;
	}
}

The output of this code is:

Index 0: kivi
Index 1: orange
Index 2: banana

As you can see, our program doesn't print apple and pear.


Assignment
Let's print all the lessons our student finished!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · LOOPING OVER ARRAY INDICES

    Break In For Loops in TypeScript, explained

    What break does

    A loop normally runs until its condition fails or its collection runs out. The break statement ends a loop sooner. When TypeScript reaches break, it leaves the innermost loop at once, without finishing the current iteration and without checking the loop's condition again. The program continues with the first statement after the loop.

    It is the right tool when the loop has already found what it was looking for, or has reached a point where the rest of the items no longer matter.

    Breaking a for...of loop

    This loop prints fruits and stops when it reaches a banana:

    let fruits = ["kivi", "orange", "banana", "apple", "pear"];
    for (let fruit of fruits) {
        console.log(fruit);
        if (fruit == "banana") {
            break;
        }
    }
    

    The output is:

    kivi
    orange
    banana
    

    The first two iterations print their fruit and the if test is false. On the third iteration fruit is "banana", the program prints it, the test is true, and break ends the loop. "apple" and "pear" are never visited.

    The same loop written with indices behaves the same way:

    for (let i = 0; i < fruits.length; i++) {
        console.log("Index " + i + ": " + fruits[i]);
        if (fruits[i] == "banana") {
            break;
        }
    }
    

    Use the index form when you need the position of the element. When the index is not needed, for...of is shorter.

    The lesson's exercise

    The starting code defines the finished lessons of a student and the last one they finished:

    let lessons: string[] = ["variables", "conditionals", "arrays", "functions", "loops"];
    let lastFinishedLesson: string = "functions";
    

    The program has to print every lesson the student finished, and stop after "functions", so "loops" is not printed. The steps:

    1. Write the loop. Use for (let lesson of lessons). The variable must be called lesson, and for...of gives the elements themselves. for...in would give the indices as strings, which is not what is wanted here.
    2. Print the lesson. Inside the loop, console.log("Finished " + lesson) joins the text and the lesson name with +.
    3. Stop after the last finished lesson. Compare lesson with lastFinishedLesson, and when they are equal, break.

    The full program:

    let lessons: string[] = ["variables", "conditionals", "arrays", "functions", "loops"];
    let lastFinishedLesson: string = "functions";
    
    for (let lesson of lessons) {
        console.log("Finished " + lesson);
        if (lesson == lastFinishedLesson) {
            break;
        }
    }
    

    It prints:

    Finished variables
    Finished conditionals
    Finished arrays
    Finished functions
    

    The order of the two statements matters. The print comes first, so the last finished lesson is printed before the loop stops. If the if came before the print, the loop would stop on "functions" without printing it, and the output would end with Finished arrays.

    Details and gotchas

    • break affects only the innermost loop. In nested loops, it ends the loop it is written in, and the outer loop carries on. The example is just below this list.
    • It works in every loop. break can be used in for, for...of, for...in, while and do...while loops, and in switch statements.
    • It does not work in forEach. The body of forEach is a function, and break is not allowed inside it. A return there skips only the current call. Use a regular loop when you may need to stop early.
    • If the condition never matches. When no element equals lastFinishedLesson, break never runs and the loop goes through the whole array. In this exercise that would print all five lessons.
    • Comparing strings. == works on two strings, as in the lesson. Many TypeScript programmers prefer ===, which also checks the type and never converts values behind the scenes.

    Break in nested loops

    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
            if (j == 1) break;
            console.log(i, j);
        }
    }
    

    This prints 0 0, 1 0 and 2 0, because each inner loop stops when j reaches 1, while the outer loop keeps going. To leave both loops at once, put a label before the outer loop and write break followed by that label.

    Remembering what you found

    A common use of break is a search. The loop stores the position of the first match in a variable declared before the loop, then stops, because later elements can't change the answer:

    function firstNegativeIndex(nums: number[]): number {
        let found = -1;
        for (let i = 0; i < nums.length; i++) {
            if (nums[i] < 0) {
                found = i;
                break;
            }
        }
        return found;
    }
    
    console.log(firstNegativeIndex([4, 7, -2, 5, -9])); // 2
    console.log(firstNegativeIndex([1, 2]));            // -1
    

    Without the break, the loop would keep going and found would end up as the index of the last negative number, 4, instead of the first.

    Key takeaways

    • break ends the innermost loop immediately.
    • Code placed before the break in the same iteration still runs, code after it does not.
    • Put the check before or after the work in the loop depending on whether the matching item should be processed.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free