TypeScript Loops
Sometimes, we may need to execute the same block of code multiple times. Normally, statements are executed sequentially: the first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
Loop statements allow us to execute a statement or group of statements multiple times. Below is the flowchart for loop statements in most programming languages:
for Loop
The TypeScript for loop is used to execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Syntax
The syntax is as follows:
for (init; condition; increment) {
statement(s);
}
Here is the control flow of the for loop:
init is executed first and only once. This step allows you to declare and initialize any loop control variables. You can also leave this empty as long as there is a semicolon.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop is not executed and control jumps to the next statement after the for loop.
After the body of the for loop executes, the control flows to the increment statement. This statement allows you to update the loop control variable. This statement can be left empty as long as there is a semicolon after the condition.
The condition is evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment, then condition evaluation). The loop terminates when the condition becomes false.
Here, statement(s) can be a single statement or a block of statements.
The condition can be any expression. The loop executes when the condition is true and exits when the condition is false.
Flowchart
Example
The following example calculates the factorial of 5. The for loop generates numbers from 5 to 1 and calculates the product of each loop iteration.
var num: number = 5;
var i: number;
var factorial = 1;
for (i = num; i >= 1; i--) {
factorial *= i;
}
console.log(factorial);
Compiling the above code yields the following JavaScript code:
var num = 5;
var i;
var factorial = 1;
for (i = num; i >= 1; i--) {
factorial *= i;
}
console.log(factorial);
Executing the above JavaScript code outputs:
120
for...in Loop
The for...in statement iterates over a set of values in a collection or list.
Syntax
The syntax is as follows:
for (var val in list) {
// statement
}
Example
var j: any;
var n: any = "a b c";
for (j in n) {
console.log(n[j]);
}
Compiling the above code yields the following JavaScript code:
var j;
var n = "a b c";
for (j in n) {
console.log(n[j]);
}
Executing the above JavaScript code outputs:
a
b
c
for...of, forEach, every, and some Loops
TypeScript also supports for...of, forEach, every, and some loops.
The for...of statement creates a loop iterating over iterable objects, introduced in ES6, which replaces for...in and forEach(), and supports the new iteration protocol. for...of allows you to iterate over Arrays, Strings, Maps, Sets, and other iterable data structures.
Example
let someArray = [1, "string", false];
for (let entry of someArray) {
console.log(entry); // 1, "string", false
}
forEach, every, and some are JavaScript loop syntaxes, and since TypeScript is a superset of JavaScript, it supports them as well.
Because forEach cannot return during iteration, you can use every and some to replace forEach.
Example
let list = [4, 5, 6];
list.forEach((val, idx, array) => {
// val: current value
// idx: current index
// array: Array
});
Example
let list = [4, 5, 6];
list.every((val, idx, array) => {
// val: current value
// idx: current index
// array: Array
return true; // Continues
// Return false will quit the iteration
});
while Loop
The while statement repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Syntax
The syntax is as follows:
while (condition) {
statement(s);
}
Here, statement(s) can be a single statement or a block of statements.
The condition can be any expression. The loop executes when the condition is true. When the condition is false, the program flow exits the loop.
Flowchart
Example
var num: number = 5;
var factorial: number = 1;
while (num >= 1) {
factorial = factorial * num;
num--;
}
console.log("The factorial of 5 is: " + factorial);
Compiling the above code yields the following JavaScript code:
var num = 5;
var factorial = 1;
while (num >= 1) {
factorial = factorial * num;
num--;
}
console.log("The factorial of 5 is: " + factorial);
Executing the above JavaScript code outputs:
The factorial of 5 is: 120
do...while Loop
Unlike the for and while loops, which test the loop condition at the top, the do...while loop checks its condition at the bottom of the loop.
Syntax
The syntax is as follows:
do {
statement(s);
} while (condition);
Note that the condition expression is at the bottom of the loop, so the statements in the loop execute at least once before the condition is tested.
If the condition is true, control flows back to the top of the do statement, and the statements in the loop execute again. This process repeats until the condition becomes false.
Flowchart
Example
var n: number = 10;
do {
console.log(n);
n--;
} while (n >= 0);
Compiling the above code yields the following JavaScript code:
var num = 5;
var n = 10;
do {
console.log(n);
n--;
} while (n >= 0);
Executing the above JavaScript code outputs:
10
9
8
7
6
5
4
3
2
1
0
break Statement
The break statement has two uses:
When the break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement stops the execution of the innermost loop and starts executing the next line of code after the block.
Syntax
The syntax is as follows:
break;
Flowchart
Example
var i: number = 1;
while (i <= 10) {
if (i % 5 == 0) {
console.log("The first number divisible by 5 between 1 and 10 is: " + i);
break; // Exit the loop after finding the first number
}
i++;
} // Outputs 5 and then the program ends
Compiling the above code yields the following JavaScript code:
var i = 1;
while (i <= 10) {
if (i % 5 == 0) {
console.log("The first number divisible by 5 between 1 and 10 is: " + i);
break; // Exit the loop after finding the first number
}
i++;
} // Outputs 5 and then the program ends
Executing the above JavaScript code outputs:
The first number divisible by 5 between 1 and 10 is: 5
continue Statement
The continue statement is similar to the break statement. Instead of forcing termination, continue forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, the continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue causes the program control to pass to the conditional tests.
Syntax
The syntax is as follows:
continue;
Flowchart
Example
var num: number = 0;
var count: number = 0;
for (num = 0; num <= 20; num++) {
if (num % 2 == 0) {
continue;
}
count++;
}
console.log("The number of odd numbers between 0 and 20 is: " + count); // Outputs 10
Compiling the above code yields the following JavaScript code:
var num = 0;
var count = 0;
for (num = 0; num <= 20; num++) {
if (num % 2 == 0) {
continue;
}
count++;
}
console.log("The number of odd numbers between 0 and 20 is: " + count); // Outputs 10
Executing the above JavaScript code outputs:
The number of odd numbers between 0 and 20 is: 10
Infinite Loop
An infinite loop is a loop that runs continuously. Both for and while loops can create infinite loops.
The syntax for creating an infinite loop with for is:
for (;;) {
// statement
}
Example
for (;;) {
// Infinite loop
}
Executing the above JavaScript code creates an infinite loop.
console.log("This code will execute endlessly")
The syntax for creating an infinite loop using while
:
while(true) {
// statements
}
Example:
while(true) {
console.log("This code will execute endlessly")
}