Skip to main content

For Loop

Introduction to For Loops in TypeScript

In TypeScript, the for loop is a control flow statement that allows code to be executed repeatedly until a certain condition is met. It's an incredibly powerful tool in programming, and learning how to use it effectively is crucial for any TypeScript beginner. This guide will walk you through everything you need to know about for loops in TypeScript, from the basic syntax to more advanced concepts.

Basic Syntax of For Loop

The for loop in TypeScript has the following syntax:

for(initialization; condition; increment/decrement) {
// code to be executed
}
  • Initialization: This is where we initialize our counter to a starting value. The initialization statement is executed only once.

  • Condition: This is evaluated before each loop iteration. If it returns true, the loop continues; otherwise, the loop stops.

  • Increment/Decrement: This updates the loop counter with a new value each time the loop runs.

Here is an example of how a for loop can be used in TypeScript:

for(let i = 0; i < 5; i++) {
console.log(i);
}

In this example, the loop starts with i at 0. After each iteration, i is incremented by 1. Once i equals 5, the loop stops. Therefore, this loop will print the numbers 0 through 4 to the console.

Nested For Loops

A for loop can be nested within another for loop to handle more complex tasks. This is often used when working with multi-dimensional arrays.

Here's an example of a nested for loop:

for(let i = 0; i < 5; i++) {
for(let j = 0; j < 5; j++) {
console.log("i: " + i + ", j: " + j);
}
}

In this example, for each iteration of i, the inner loop will execute 5 times because of j < 5, resulting in a total of 25 iterations.

The Break Statement

The break statement can be used to end a for loop prematurely. When a break statement is encountered, the loop stops, and control skips to the line immediately following the loop.

Here's an example of a for loop with a break statement:

for(let i = 0; i < 10; i++) {
if(i === 5) {
break;
}
console.log(i);
}

In this example, the loop will stop when i equals 5, so the numbers 0 through 4 will be printed to the console.

The Continue Statement

The continue statement can be used to skip one iteration of the loop. It continues with the next iteration of the loop.

Here's an example of a for loop with a continue statement:

for(let i = 0; i < 10; i++) {
if(i === 5) {
continue;
}
console.log(i);
}

In this example, when i equals 5, the current iteration will be skipped, and the loop will continue with the next value of i.

Conclusion

The for loop in TypeScript is a powerful control flow tool that is essential for handling repetitive tasks in your code. By understanding the basics and learning how to utilize nested loops, break and continue statements, you can write more efficient and cleaner code. Happy coding!