Typescript continue statement
Created By: chatGPT
In TypeScript, the
continue
statement is used in loops to skip the current iteration and proceed to the next one. This can be particularly useful when dealing with conditional logic where certain conditions should bypass further processing within the loop. Here’s how to use it effectively.for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // This will only log odd numbers
}
In this example, a for loop iterates over the numbers from 0 to 9. The
if (i % 2 === 0)
condition checks if the current number i
is even. If it is, the continue
statement is executed, which causes the loop to skip the console.log(i)
statement for that iteration, resulting in only odd numbers being printed.for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip processing even numbers
}
console.log(i); // Output: 1, 3, 5, 7, 9
}
The continue statement can also be used in other types of loops, such as while or do-while. Here’s an example using a while loop:
let i = 0;
while (i < 10) {
i++;
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // Output: 1, 3, 5, 7, 9
}
In the while loop example, the variable
i
is incremented first, and then it checks if i
is even. If it is, the continue
statement occurs, skipping the logging for even numbers. This demonstrates how the use of continue
can streamline your code by avoiding deeper nesting of if
statements.let i = 0;
while (i < 10) {
i++;
if (i % 2 === 0) {
continue;
}
console.log(i); // Executes only for odd numbers
}