Break Statement in TypeScript
In this tutorial, we will learn about the break statement in TypeScript. We will cover the basics of using the break statement to exit loops prematurely.
What is a Break Statement
A break statement is used to terminate the execution of a loop. When a break statement is encountered, the loop immediately terminates, and the program continues with the next statement following the loop.
Syntax
The syntax for the break statement in TypeScript is:
break;
The break statement can be used in for, while, and do-while loops to exit the loop prematurely.
Example 1: Exiting a For Loop Early
- Use a for loop to iterate over a range of numbers from 1 to 10.
- Inside the loop, use an if statement to check if the current number is equal to 5.
- If the condition is true, use a break statement to exit the loop.
- Print the current number.
TypeScript Program
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
Output
1 2 3 4
Example 2: Exiting a While Loop Early
- Declare a variable
i
and initialize it to 1. - Use a while loop to iterate while
i
is less than or equal to 10. - Inside the loop, use an if statement to check if
i
is equal to 5. - If the condition is true, use a break statement to exit the loop.
- Print the value of
i
.
TypeScript Program
let i = 1;
while (i <= 10) {
if (i === 5) {
break;
}
console.log(i);
i++;
}
Output
1 2 3 4
Example 3: Exiting a Do-While Loop Early
- Declare a variable
i
and initialize it to 1. - Use a do-while loop to iterate.
- Inside the loop, use an if statement to check if
i
is equal to 5. - If the condition is true, use a break statement to exit the loop.
- Print the value of
i
.
TypeScript Program
let i = 1;
do {
if (i === 5) {
break;
}
console.log(i);
i++;
} while (i <= 10);
Output
1 2 3 4