Loops in TypeScript
In the previous article of our TypeScript series, we explored the topic of operators in TypeScript. Today, we’ll examine the issue of loops in TypeScript.
It will be no surprise to you that TypeScript is equipped with different types of loops. In TypeScript, we can divide loops into two categories: definite and indefinite. In the category of the former, we’ll look at the for loop, and in the latter category, we’ll look at both while and do while loops. We’ll also look at break and continue statements and infinite loops.
For Loops in TypeScript
We call for loops definite because they have a predetermined number of iterations. For loops in TypeScript execute a block of code a set number of times. They have several purposes and are often found in code that iterates over a fixed set of values, like an array for example. The syntax of the for loop in TypeScript is as follows:
for (initial_count_value; termination-condition; step) {
//statements go here
}
For loops in TypeScript use a count variable for keeping track of the iterations. The iteration is initialized by setting the value of count to an initial value. Then, so long as the value of count meets the termination condition, the code block is executed. Finally, step changes the value of count at the end of each iteration. Here is an example that should help to clarify:
var num:number = 5;
var i:number;
var factorial = 1;
for(i = num;i>=1;i--) {
factorial *= i;
}
console.log(factorial)
This code calculates the factorial of the number 6 and then prints out the result in the console. The for loop generates a sequence of numbers from 1 to 6 and then calculates the product of the numbers in every iteration.
Once compiled, it will generate following JavaScript:
"use strict";
var num = 4;
var i;
var factorial = 1;
for (i = num; i >= 1; i--) {
factorial *= i;
}
console.log(factorial);
This code gives the following output in the console:
720
The For In Loop
In TypeScript, there exists an alternative to the standard for loop. This is the for in loop which can be used to iterate over a set of values such as an array or even a tuple. TypeScript’s for in loop can also be used to iterate through a list or collection of values. Here is how the syntax of the for in loop looks:
for (var val in list) {
//statements
}
Now, let’s turn to an example.
var j:any;
var n:any = "x y z"
for(j in n) {
console.log(n[j])
}
Notice how nice the TypeScript code looks compared to the JavaScript below:
"use strict";
var j;
var n = "x y z";
for (j in n) {
console.log(n[j]);
}
This will return the following to the console:
x
y
z
The While Loop in TypeScript
In TypeScript, a while loop executes the conditional code each time that the specified condition evaluates to true. This means that the condition is evaluated before the block of code is executed. Here is how the syntax looks:
while(condition) {
// statements executed if the condition is true
}
Now here’s our example:
var num:number = 6;
var factorial:number = 1;
while(num >=1) {
factorial = factorial * num;
num--;
}
console.log("The factorial equals: "+factorial);
And here is the JavaScript that is generated:
"use strict";
var num = 6;
var factorial = 1;
while (num >= 1) {
factorial = factorial * num;
num--;
}
console.log("The factorial equals: " + factorial);
Finally, the output to the console:
The factorial equals: 720
The Do While Loop in TypeScript
TypeScript has a second kind of indefinite loop that is similar to the while loop. This is of course the do while loop!
These two TypeScript loops are similar but differ in that the do while loop doesn’t evaluate the condition when the loop runs for the first time. The condition is of course evaluated with each iteration coming afterward. So in a do while loop, the code block will be executed at least once.
Let’s have a look at a quick example:
var x:number = 7;
do {
console.log(x);
x--;
} while(x>=0);
And the JavaScript:
"use strict";
var x = 7;
do {
console.log(x);
x--;
} while (x >= 0);
Finally, the result in the console:
7
6
5
4
3
2
1
0
Let’s look at another example to help clarify the difference between the while and do while loops in TypeScript.
var x:number = 6
while(x > 6) {
console.log("We're in the while loop!")
}
do {
console.log("We're in the do while loop!")
}
while(x>6)
The example starts by declaring a while loop. We enter this loop only if we pass an expression that is true to while. Since the value of x is less than zero, the expression returns false and we don’t enter the loop.
But look at the the do…while loop. It executes the statement once. This is because the initial iteration does not consider the boolean expression. However, in the subsequent iteration, the while checks the condition and takes the control out of the loop.
Here’s the JavaScript:
"use strict";
var x = 6;
while (x > 6) {
console.log("We're in the while loop!");
}
do {
console.log("We're in the do while loop!");
} while (x > 6);
And the console:
We're in the do while loop!
Now that we’ve covered some basic loop types, let’s look at some related issues.
Break Statements in TypeScript
Break statements in TypeScript are used to take the control out of a construct. Using a break statement in a loop causes the program to exit out of the loop. Its syntax is simply the word ‘break.’
Here’s a quick example:
var i:number = 1
while(i<=16) {
if (i % 4 == 0) {
console.log ("The first multiple of 4 between 1 and 16 is: "+i)
break //exit the loop if the first multiple is found
}
i++
} //outputs 4 and exits the loop
Once compiled, the JavaScript will look like this:
"use strict";
var i = 1;
while (i <= 16) {
if (i % 4 == 0) {
console.log("The first multiple of 4 between 1 and 16 is: " + i);
break; //exit the loop if the first multiple is found
}
i++;
} //outputs 4 and exits the loop
And in the console you’ll receive:
The first multiple of 4 between 1 and 16 is: 4
Continue Statements in TypeScript:
The continue statement skips over any subsequent statements in the current iteration and bring the control back to the start of the loop. As opposed to break statements, continue statements in TypeScript doesn’t exit the loop. They just terminate the current iteration and then start the subsequent iteration.
Again the syntax is quite simple: just the keyword 'continue.’
Here is our example that returns the number of even values between 0 and 10. We exit the loop during the iteration where the number is ever by making use of the continue statement.
var num:number = 0
var count:number = 0;
for(num=0;num<=10;num++) {
if (num % 2==0) {
continue
}
count++
}
console.log (" The number of odd values between 0 and 10 is: "+count) //outputs 5
The JavaScript:
"use strict";
var num = 0;
var count = 0;
for (num = 0; num <= 10; num++) {
if (num % 2 == 0) {
continue;
}
count++;
}
console.log(" The number of odd values between 0 and 10 is: " + count); //outputs 5
And finally the output in the console:
The number of odd values between 0 and 10 is: 5
That does it for this time. Check back soon for the next article in the series where we’ll start to look at functions in TypeScript. See you then!
Recent Stories
Top DiscoverSDK Experts
Compare Products
Select up to three two products to compare by clicking on the compare icon () of each product.
{{compareToolModel.Error}}
{{CommentsModel.TotalCount}} Comments
Your Comment