Skip to content

TypeScript - Loops

Loops are control flow structures used to execute a block of code repeatedly. This is essential when you need to perform the same action multiple times, such as iterating over array elements or processing data until a specific condition is met.

TypeScript supports the standard looping constructs found in JavaScript.

Loops can be broadly categorized:

  • Definite Loops: Execute a known number of times (e.g., standard for loop).
  • Indefinite Loops: Execute until a specific condition becomes false (e.g., while, do...while).
  • Iteration Loops: Specifically designed for iterating over collections (e.g., for...of, for...in, forEach method).

The classic for loop is ideal when you know how many times you want to iterate.

for (initialization; condition; increment/decrement) {
// code block to be executed
}
  • initialization: Executed once before the loop starts (e.g., let i = 0).
  • condition: Evaluated before each iteration. If true, the loop continues; if false, it stops.
  • increment/decrement: Executed after each iteration (e.g., i++, i--, i += 2).
console.log("Standard for loop:");
for (let i: number = 0; i < 5; i++) {
console.log(`Iteration number: ${i}`);
}
// Output: 0, 1, 2, 3, 4

Executes a block of code as long as a specified condition remains true. The condition is checked before each iteration.

while (condition) {
// code block to be executed
}
let counter: number = 0;
console.log("\nWhile loop:");
while (counter < 3) {
console.log(`Counter is: ${counter}`);
counter++;
}
// Output: 0, 1, 2

Similar to while, but the condition is checked after the code block executes. This guarantees the block runs at least once, even if the condition is initially false.

do {
// code block to be executed
} while (condition);
let attempts: number = 5;
console.log("\nDo...while loop:");
do {
console.log(`Attempt number: ${attempts}`);
attempts++;
} while (attempts < 5);
// Output: Attempt number: 5 (runs once even though condition 5 < 5 is false)

The modern and preferred way to iterate over the values of iterable objects like arrays, strings, maps, sets, etc.

for (const element of iterable) {
// code block using element
}
const iterableData: string[] = ["A", "B", "C"];
console.log("\nFor...of loop:");
for (const item of iterableData) {
console.log(`Item: ${item}`);
}
// Output: A, B, C

Iterates over the keys (property names or array indices as strings) of an object.

Caution: Generally avoid using for...in for arrays, as it iterates over indices as strings and might include inherited properties. Use for...of or forEach for arrays. It’s more suited for iterating over object properties.

for (const key in object) {
// code block using key and potentially object[key]
// Optional: check if property is own property: if (object.hasOwnProperty(key)) { ... }
}
const userObject = { name: "David", age: 40, city: "New York" };
console.log("\nFor...in loop (object properties):");
for (const propName in userObject) {
// Use type assertion or checking if accessing value dynamically
console.log(`${propName}: ${userObject[propName as keyof typeof userObject]}`);
}
// Output: name: David, age: 40, city: New York (order not guaranteed)

These statements alter the normal execution flow within loops:

Immediately terminates the innermost loop (for, while, do...while, switch) it’s contained within. Execution continues at the statement following the terminated loop.

console.log("\nBreak example:");
for (let i = 0; i < 10; i++) {
if (i === 5) {
console.log("Breaking loop at i=5");
break; // Exit the loop
}
console.log(i);
}
// Output: 0, 1, 2, 3, 4, Breaking loop at i=5

Skips the rest of the current iteration of the loop and proceeds to the next iteration. The loop’s condition (if applicable) is re-evaluated.

console.log("\nContinue example:");
for (let i = 0; i < 5; i++) {
if (i % 2 !== 0) {
continue; // Skip odd numbers
}
console.log(`Even number: ${i}`);
}
// Output: Even number: 0, Even number: 2, Even number: 4

A loop whose condition never becomes false will run forever, potentially crashing the program or browser tab. Ensure your loop conditions eventually evaluate to false or use break appropriately.

// Example of an intentional infinite loop (e.g., in a server waiting for requests)
// while (true) {
// console.log("Running forever...");
// // Usually contains logic and potentially a break condition
// }
// Example of an accidental infinite loop
// let k = 0;
// while (k < 5) {
// console.log(k);
// // Forgot to increment k, so k < 5 is always true!
// }