TypeScript - Loops
TypeScript - Loops
Section titled “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.
Types of Loops
Section titled “Types of Loops”Loops can be broadly categorized:
- Definite Loops: Execute a known number of times (e.g., standard
forloop). - 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,forEachmethod).
The for Loop
Section titled “The for Loop”The classic for loop is ideal when you know how many times you want to iterate.
Syntax
Section titled “Syntax”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. Iftrue, the loop continues; iffalse, it stops.increment/decrement: Executed after each iteration (e.g.,i++,i--,i += 2).
Example
Section titled “Example”console.log("Standard for loop:");for (let i: number = 0; i < 5; i++) { console.log(`Iteration number: ${i}`);}// Output: 0, 1, 2, 3, 4The while Loop
Section titled “The while Loop”Executes a block of code as long as a specified condition remains true. The condition is checked before each iteration.
Syntax
Section titled “Syntax”while (condition) { // code block to be executed}Example
Section titled “Example”let counter: number = 0;console.log("\nWhile loop:");while (counter < 3) { console.log(`Counter is: ${counter}`); counter++;}// Output: 0, 1, 2The do...while Loop
Section titled “The do...while Loop”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.
Syntax
Section titled “Syntax”do { // code block to be executed} while (condition);Example
Section titled “Example”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 for...of Loop
Section titled “The for...of Loop”The modern and preferred way to iterate over the values of iterable objects like arrays, strings, maps, sets, etc.
Syntax
Section titled “Syntax”for (const element of iterable) { // code block using element}Example
Section titled “Example”const iterableData: string[] = ["A", "B", "C"];console.log("\nFor...of loop:");for (const item of iterableData) { console.log(`Item: ${item}`);}// Output: A, B, CThe for...in Loop
Section titled “The for...in Loop”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.
Syntax
Section titled “Syntax”for (const key in object) { // code block using key and potentially object[key] // Optional: check if property is own property: if (object.hasOwnProperty(key)) { ... }}Example
Section titled “Example”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)Loop Control Statements
Section titled “Loop Control Statements”These statements alter the normal execution flow within loops:
The break Statement
Section titled “The break Statement”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=5The continue Statement
Section titled “The continue Statement”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: 4Infinite Loops
Section titled “Infinite Loops”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!// }