TypeScript Loops
Loop statements are used to repeatedly execute a block of code until a specific exit condition is met. TypeScript supports multiple loop structures, the same as loops in JavaScript.
1. for Loop
The for loop is the most commonly used and flexible loop type. It consists of three parts: initialization, condition, and increment/decrement expression.
Syntax
- initialization: Executed once before the loop starts, typically used to initialize a counter variable.
- condition: Evaluated before each loop iteration begins. If
true, the loop body executes. Iffalse, the loop terminates. - increment/decrement: Executed after each loop iteration ends, typically used to update the counter.
Example
2. while Loop
The while loop continues to execute a code block while the specified condition is true.
Syntax
The condition is checked before each loop iteration begins. If the condition is false from the start, the loop body will never execute.
Example
3. do...while Loop
The do...while loop is similar to the while loop, but it guarantees the loop body executes at least once because the condition is checked after the loop body executes.
Syntax
Example
4. for...of Loop
The for...of loop (introduced in ES6) is used to iterate over element values of iterable objects (like arrays, strings, Map, Set, etc.).
Syntax
Example
5. for...in Loop
The for...in loop is used to iterate over all enumerable property keys of an object.
Syntax
Example
Note: for...in should not be used to iterate over arrays because it may iterate over indexes in unexpected order and may include non-numeric keys. For array iteration, prefer for, for...of, or array methods (like forEach).
Loop Control Statements
break: Immediately terminates the current loop.continue: Skips the current iteration of the loop and begins the next iteration.