TypeScript Repetition Statements

TypeScript Repetition Statements

This article explains the repetition statements in TypeScript.

YouTube Video

The for statement in TypeScript

The for statement in TypeScript is a basic loop structure for performing repeated operations. In a for loop, the same block of code can be repeatedly executed based on a specified number of times or conditions.

Basic Syntax

1for (initialization; condition; update) {
2    // Code to execute repeatedly while the condition is true
3}
  • Initialization (initialization): The part that is executed only once before starting the loop. Initialize variables such as the loop counter.
  • Condition (condition): The condition that determines whether to continue the loop. If true, the loop continues; if false, it ends.
  • Update (update): This is executed at the end of each loop to update the loop counter.

Example 1: Basic for loop

In the example below, it outputs the numbers from 0 to 4 in order.

1for (let i = 0; i < 5; i++) {
2    console.log("The value of i is: " + i);
3}
4// Outputs:
5// The value of i is: 0
6// The value of i is: 1
7// The value of i is: 2
8// The value of i is: 3
9// The value of i is: 4

Example 2: for loop with an array

You can also use a for loop to process the elements of an array in order.

1let fruits: string[] = ["apple", "banana", "cherry"];
2
3for (let i = 0; i < fruits.length; i++) {
4    console.log("Fruit: " + fruits[i]);
5}
6// Outputs:
7// Fruit: apple
8// Fruit: banana
9// Fruit: cherry

Example 3: for-in loop

The for-in loop is used to iterate over the properties of an object or the indices of an array in order.

1let car = { brand: "Toyota", model: "Corolla", year: 2020 };
2
3for (let key in car) {
4    console.log(key + ": " + car[key]);
5}
6// Outputs:
7// brand: Toyota
8// model: Corolla
9// year: 2020

Example 4: for-of loop

The for-of loop is used to get each element's value in order from iterable objects such as arrays or strings.

1let colors: string[] = ["red", "green", "blue"];
2
3for (let color of colors) {
4    console.log("Color: " + color);
5}
6// Outputs:
7// Color: red
8// Color: green
9// Color: blue

Example 5: Nested for Loop

It is also possible to use a for loop within another for loop, known as a nested loop. This allows you to create double loops, among other things.

 1for (let i = 0; i < 3; i++) {
 2    console.log("Outer loop i: " + i);
 3    for (let j = 0; j < 2; j++) {
 4        console.log("  Inner loop j: " + j);
 5    }
 6}
 7// Outputs:
 8// Outer loop i: 0
 9//   Inner loop j: 0
10//   Inner loop j: 1
11// Outer loop i: 1
12//   Inner loop j: 0
13//   Inner loop j: 1
14// Outer loop i: 2
15//   Inner loop j: 0
16//   Inner loop j: 1

Summary

  • The for statement performs repetitive processing based on specified counts or conditions.
  • for-in is used to retrieve the properties of an object or the indexes of an array.
  • for-of retrieves the values of elements from iterable objects like arrays.
  • Complex repetitive processing is also possible with nested for loops.

The for statement in TypeScript provides powerful and flexible repetitive processing, similar to other loops.

While Statements in TypeScript

In TypeScript, a while statement is a loop construct that executes a repetitive process while the specified condition is true. Similar to the for loop, the while loop is suitable for cases where the number of iterations is not predetermined, or when you want to control repetition based on a condition.

Basic Syntax

1while (condition) {
2    // Code to execute repeatedly while the condition is true
3}
  • Condition: The condition under which the loop executes. The loop continues as long as this condition is true, and stops when it becomes false.

Example 1: Basic while Loop

In the example below, it continues to output the value of i while i is less than 5.

 1let i: number = 0;
 2
 3while (i < 5) {
 4    console.log("The value of i is: " + i);
 5    i++;
 6}
 7// Outputs:
 8// The value of i is: 0
 9// The value of i is: 1
10// The value of i is: 2
11// The value of i is: 3
12// The value of i is: 4

In this example, the loop ends when i becomes 5 or greater because the condition becomes false.

Example 2: Infinite Loop Example

If the condition in a while loop is always true, it can become an infinite loop. This usually causes the program to fail to stop as intended, so caution is needed.

 1let x: number = 0;
 2
 3while (true) {
 4    console.log("The value of x is: " + x);
 5    x++;
 6    if (x >= 5) {
 7        break; // Exit the loop when the condition is met
 8    }
 9}
10// Outputs:
11// The value of x is: 0
12// The value of x is: 1
13// The value of x is: 2
14// The value of x is: 3
15// The value of x is: 4

You can use the break statement to forcibly exit the loop when a condition is met.

Example 3: do-while Loop

The do-while loop is a structure where the loop process is executed at least once. Since the condition is evaluated after the process, the process runs at least once even if the condition is false.

1let j: number = 5;
2
3do {
4    console.log("The value of j is: " + j);
5    j++;
6} while (j < 5);
7// Outputs: The value of j is: 5

In this example, j is 5 from the start, and j < 5 is false, but in a do-while loop, it runs at least once regardless of the condition.

Summary

  • A while loop repeats processing as long as the condition is true.
  • If the loop termination condition is unclear, you need to be careful of infinite loops.
  • A do-while loop differs from a normal while loop in that the processing is executed at least once.

The while statement in TypeScript is useful for loop processing with uncertain iteration counts or when dynamic condition checking is necessary.

break and continue

You can use break and continue within loops.

  • break is used to terminate a loop prematurely.
  • continue is used to skip the current iteration and move to the next iteration.

Example of break

 1for (let i = 0; i < 10; i++) {
 2    if (i === 5) {
 3        break;  // Exits the loop when i is 5
 4    }
 5    console.log(i);
 6}
 7// Outputs 0, 1, 2, 3, 4
 8
 9let i = 0;
10while (i < 10) {
11    if (i === 5) {
12        break;  // Ends the loop when i is 5
13    }
14    console.log(i);
15    i++;
16}
17// Outputs 0, 1, 2, 3, 4

In this case, break is executed when i becomes 5. As a result, numbers from 0 to 4 are displayed.

Example of continue

 1for (let i = 0; i < 5; i++) {
 2    if (i === 2) {
 3        continue;  // Skips when i is 2
 4    }
 5    console.log(i);
 6}
 7// Outputs 0, 1, 3, 4
 8
 9let i = 0;
10while (i < 5) {
11    if (i === 2) {
12        i++;
13        continue;  // Skips when i is 2
14    }
15    console.log(i);
16    i++;
17}
18// Outputs 0, 1, 3, 4

In this case, continue is executed when i is 2. As a result, numbers except 2 are displayed.

Nested loops in TypeScript

A nested loop is a structure where a loop is used inside another loop. In TypeScript, loop constructs such as for, while, and do-while are supported. By using nested loops, you can process two-dimensional arrays (matrices) and streamline processing based on multiple conditions.

Basic Syntax

The basic syntax of a nested loop is as follows.

1for (let i: number = 0; i < n; i++) {
2    for (let j: number = 0; j < m; j++) {
3        // Processing for the inner loop
4    }
5}

For each execution of the outer loop, the inner loop completes all its iterations. This structure is very useful when handling multiple loops or data structures.

Example of a nested loop in TypeScript

Traversing a two-dimensional array

Nested loops are often used when manipulating multidimensional data structures like two-dimensional arrays. In the following example, elements of a two-dimensional array are traversed, and their values are displayed on the console.

 1const matrix: number[][] = [
 2    [1, 2, 3],
 3    [4, 5, 6],
 4    [7, 8, 9]
 5];
 6
 7for (let row: number = 0; row < matrix.length; row++) {
 8    for (let col: number = 0; col < matrix[row].length; col++) {
 9        console.log(`matrix[${row}][${col}] = ${matrix[row][col]}`);
10    }
11}
12// Output
13// matrix[0][0] = 1
14// matrix[0][1] = 2
15// matrix[0][2] = 3
16// matrix[1][0] = 4
17// matrix[1][1] = 5
18// matrix[1][2] = 6
19// matrix[2][0] = 7
20// matrix[2][1] = 8
21// matrix[2][2] = 9

In this example, we are traversing the two-dimensional array matrix. The outer loop handles the rows, and the inner loop handles the columns, displaying each element in order.

Combination of two arrays

Next, we introduce an example of calculating all combinations of two arrays. For instance, you can take one element from each of two arrays and output all possible pairs.

 1const array1: string[] = ['A', 'B', 'C'];
 2const array2: number[] = [1, 2, 3];
 3
 4for (let i: number = 0; i < array1.length; i++) {
 5    for (let j: number = 0; j < array2.length; j++) {
 6        console.log(`Pair: (${array1[i]}, ${array2[j]})`);
 7    }
 8}
 9// Output
10// Pair: (A, 1)
11// Pair: (A, 2)
12// Pair: (A, 3)
13// Pair: (B, 1)
14// Pair: (B, 2)
15// Pair: (B, 3)
16// Pair: (C, 1)
17// Pair: (C, 2)
18// Pair: (C, 3)

In this example, all pairs between the string array array1 and the number array array2 are created. The outer loop extracts elements from array1, and the inner loop extracts elements from array2, displaying each pair.

Generating coordinates with a triple loop

By using triple nested loops, you can generate coordinates in a three-dimensional space, for example.

 1for (let x: number = 0; x < 3; x++) {
 2    for (let y: number = 0; y < 3; y++) {
 3        for (let z: number = 0; z < 3; z++) {
 4            console.log(`Coordinate: (${x}, ${y}, ${z})`);
 5        }
 6    }
 7}
 8// Output
 9// Coordinate: (0, 0, 0)
10// Coordinate: (0, 0, 1)
11// Coordinate: (0, 0, 2)
12// ...
13// Coordinate: (2, 2, 1)
14// Coordinate: (2, 2, 2)

In this way, using triple nested loops allows you to easily generate coordinates in a three-dimensional space.

Performance of nested loops

Nested loops are convenient, but the computational cost increases rapidly as the depth of loops increases. For example, if there are n iterations of the outer loop and m iterations of the inner loop, the total number of iterations will be n * m. When this becomes further nested, the computational complexity increases exponentially, potentially affecting program performance.

Below are the computational complexities when traversing three arrays.

 1const array1: number[] = [1, 2, 3];
 2const array2: number[] = [4, 5, 6];
 3const array3: number[] = [7, 8, 9];
 4
 5for (let i: number = 0; i < array1.length; i++) {
 6    for (let j: number = 0; j < array2.length; j++) {
 7        for (let k: number = 0; k < array3.length; k++) {
 8            console.log(`Combination: (${array1[i]}, ${array2[j]}, ${array3[k]})`);
 9        }
10    }
11}

In this case, the loop runs a number of times equal to the product of the lengths of array1, array2, and array3, resulting in a total of 27 iterations to process all combinations.

Optimization of nested loops

When using nested loops, you can improve performance by considering the following optimizations.

  1. Introduce early returns: Exit the loop early when the goal is achieved to avoid unnecessary iterations.
  2. Cache loop variables: Pre-cache the values of variables used within the loop (especially lengths and ranges) to reduce the cost of computation each time.
  3. Change data structures: Revising the structure of arrays and objects can be effective in speeding up specific repetitive processes.

Conclusion

Nested loops are a powerful tool in complex data processing and algorithms. However, as loop depth and the number of iterations increase, performance issues may arise. With appropriate optimizations and careful design, you can effectively leverage nested loops in TypeScript.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video