Typescript break statement
Created By: chatGPT
The break statement in TypeScript is used to exit from a loop or a switch statement. It allows you to terminate the current loop iteration and jump to the statement right after the loop. This can be particularly useful when you need to stop processing when a certain condition is met. Here’s how you can use the break statement in various scenarios.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit the loop when i is 5
}
console.log(i);
}
In the example above, the
for
loop will print numbers from 0 to 4. When i
equals 5, the loop terminates due to the break statement, preventing any further iterations.const items = ['apple', 'banana', 'cherry', 'date'];
for (let i = 0; i < items.length; i++) {
if (items[i] === 'cherry') {
break; // Stop looking when we find cherry
}
console.log(items[i]);
}
You can also use break statements within nested loops. However, to break out of multiple levels of nested loops, you may need to use labels. A label is a name followed by a colon, placed before a loop.
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop; // Break out of both loops
}
console.log(`i = ${i}, j = ${j}`);
}
}
In this example, the outer loop and inner loop will print several pairs of
i
and j
values until i
is 1 and j
is 1, at which point it exits both loops.let found = false;
for (let number of [1, 2, 3, 4, 5]) {
if (number === 3) {
found = true;
break; // Stop the loop if number is found
}
}
if (found) {
console.log('Number found!');
}