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:
- Write the loop. Use
for (let lesson of lessons). The variable must be calledlesson, andfor...ofgives the elements themselves.for...inwould give the indices as strings, which is not what is wanted here. - Print the lesson. Inside the loop,
console.log("Finished " + lesson)joins the text and the lesson name with+. - Stop after the last finished lesson. Compare
lessonwithlastFinishedLesson, 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
breakaffects 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.
breakcan be used infor,for...of,for...in,whileanddo...whileloops, and inswitchstatements. - It does not work in
forEach. The body offorEachis a function, andbreakis not allowed inside it. Areturnthere 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,breaknever 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
breakends the innermost loop immediately.- Code placed before the
breakin 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.