Typescript while loop
Created By: chatGPT
TypeScript offers a powerful way to use loops to execute a block of code multiple times. The
while
loop continues to execute the given block as long as the specified condition evaluates to true. To understand how to use a while
loop in TypeScript, consider the structure below.let count = 0;
while (count < 5) {
console.log(`Count is: ${count}`);
count++;
}
In this example, we initialize a variable
count
to zero. The while
loop checks if count
is less than 5. If the condition is true, it executes the code inside the block, which logs the current value of count
and then increments it by 1. Once count
reaches 5, the loop stops executing.// Output:
// Count is: 0
// Count is: 1
// Count is: 2
// Count is: 3
// Count is: 4
It’s essential to ensure that the condition will eventually become false; otherwise, the loop will result in an infinite loop. For example, if count++ were omitted, the loop would never terminate.
let num = 0;
while (num < 5) {
console.log(num);
// Missing num++ would result in an infinite loop
}
You can also perform more complex logic inside the loop. For example, let's create a loop that sums numbers until a certain limit.
let sum = 0;
let limit = 10;
let i = 1;
while (i <= limit) {
sum += i;
i++;
}
console.log(`Total Sum: ${sum}`);
In this snippet, we initialize
To summarize, the sum
, define a limit
, and start counting with i
. As long as i
is less than or equal to limit
, we keep adding i
to sum
and increment i
. After the loop finishes, we log the total sum.// Output:
// Total Sum: 55
while
loop is a simple yet effective control structure in TypeScript that you can leverage for repeated tasks. Just remember to make sure that your condition will eventually become false to avoid an infinite loop.