TypeScript for, while & do while loops Tutorial

In this TypeScript tutorial we learn how to repeat sections of our code with for, while and do while loops based on the results of a condition.

We discuss nesting loops and lastly, we learn how to refine control on our loops by using the break and continue statements.

What is iteration control and looping

We can control the flow of our application even further by looping through sections of code when a condition proves true.

As an example, let’s consider a database of users that are subscribed to a mailing list.

Normally, we would enter a user’s email address, copy-paste a predefined message, and then send the email.

But, there could be tens of thousands of users in that list. We would need a way to automate the process.

Iteration control allows us to set up that process in code, then repeat it by looping through all the users on the list, sending them each an email.

TypeScript provides us with three different kinds of loops:

  • while - This loop iterates through a section of code while a condition is true.
  • do while - This loop is the same as the while loop but with a single forced loop at the start.
  • for - This loop iterates through a section of code a set number of times.

The indefinite while loop

A while loop is used when we don’t know how many times a loop will repeat, like the number of users in a database.

A while loop will keep looping through its code, while a specified condition is true. For example, while there are users in a database, loop through the section of code that sends an email.

To write a while loop, we use the keyword while , followed by the condition in between parentheses, and a code block that contains the code we want to execute on each iteration.

Syntax:
while (condition) {

  // execution statement(s)
}
Example:
let i: number = 1

while (i <= 10) {
  console.log("Iteration no: " + i)
  i++
}

When we run the example above, we should see the following output.

Output:
Iteration no: 1
Iteration no: 2
Iteration no: 3
Iteration no: 4
Iteration no: 5
Iteration no: 6
Iteration no: 7
Iteration no: 8
Iteration no: 9
Iteration no: 10

The single section of code we wrote in the code block was repeated 10 times.

Let’s break down the example above step by step.

  1. First, we set up a variable called i with the number 1. This variable will act as a counter, and help us see which iteration of the entire loop we’re on.
  2. Then, we specify our condition. While the value of i is less than or equal to 10, execute the code in the code block.
  3. In the code block we have a simple statement that prints the number i . We also increment it by one by adding ++ to it.

What will happen is the following:

  1. The compiler will see that i is 1. This means the loop condition is true, so it will print the message to the page and increment i by 1.
  2. Then, it will move back to the start of the loop and evaluate the condition again. The condition is still true because i , now 2, is still less than 10, so it executes the code block again.
  3. This continues until i is 10, in which case the condition turns false and the compiler stops looping.

Let’s try a more practical example.

Example:
// counter
let i : number = 0
// list of users
let user : string[] = ["John", "Jane", "Jack", "Jill"]

// while there are users in the list
// print their names to the console
while (user[i]) {
  console.log("User:", user[i])
  i++
}

We will pretend for the moment that the names in the user array comes from a database. Our condition is slightly different than before.

The compiler will automatically stop looping when it reaches the end of the array, so we don’t have to specify explicitly how many times it should loop.

All we have to do is increment the counter that loops through the users.

note We cover looping again in the tutorial lesson on Arrays .

The indefinite do-while loop

The do while loop is sort of like an upside down while loop. The execution code is specified first, then the condition is checked.

To write a do while loop we use the keyword do , followed by a code block with the execution code. Then, we specify the while condition.

Syntax:
do {
  // execution code
} while (condition);

note Because the do while statement doesn’t end with a curly brace, it’s terminated with a semicolon.

Example:
let i: number = 1

do  {
  console.log("Iteration no: ", i)
  i++
} while (i <= 0);

In the example above we set the counter to 1. But, the condition will check if the counter is less than or equal to 0, so the condition is always false and the loop shouldn’t run.

When we compile and run the script however, we see that the loop did run once. This is because the code block is executed before the compiler could evaluate the condition and stop the loop.

note A do while loop will always run at least once.

The definite for loop

A for loop is used when we know how many times the loop will repeat, like the number of hours in a day.

The syntax in a for loop is much more compact. It has the counter, the condition, and the increment all in one place.

We write the keyword for , followed by a condition block and then an execution block containing the code we want to have loop.

Inside the condition block in the header we first set up our counter, followed by a semicolon terminator. Then we specify our condition, again followed by a semicolon terminator. Lastly, we increment/decrement the counter.

Syntax:
for (counter_setup; condition; counter_increment) {
  // execution code
}
Example:
for (let i: number = 1; i <= 10; i++) {
  console.log("Iteration no: ", i)
}

The example above is exactly the same as our first while loop example, the only difference is the syntax. The counter setup and counter increment is done inside the condition block.

In a while loop we may not always need a counter. But, in a for loop we will always need a counter so the setup and increment is required.

How to nest loops

Similar to nesting conditional control statements, we can nest loops inside other loops.

The loops will be executed hierarchically, which means the compiler will run an inner loop fully, before it moves on to the next iteration of the outer loop.

As an example, let’s consider that we want to create a chunk of blocks like those in Minecraft.

We want it to be 16 x 16 blocks on the x and z axis (a square) and we want it to be 16 blocks high on the y axis.

We would need to create blocks in each of the three axes, x, y and z. For that we would need to nest our loops.

Example:
// 16 x 16 x 16 square
let xSize : number = 16
let ySize : number = 16
let zSize : number = 16

for (var x : number = 0; x <= xSize; x++)  {

  for (var y : number = 0; y <= ySize; y++)  {

    for (var z : number = 0; z <= zSize; z++)  {

      // code to create blocks
      console.log("x: ", x, " - y: ", y, " - z: ", z)
    }
  }
}

In the example above, we print a message with the block number created on each axis.

tip We shouldn’t nest more than three levels deep. Nesting too deep is considered a bad practice and can become complicated very quickly.

Loop control statements: break

TypeScript provides us with control statements to control the flow of our loops. The first of these statements is the break statement.

The break control statement allows us to break out of a loop at any point, by using the keyword break where we want to break out of the loop.

Example:
for (let x: number = 0; x <= 10; x++) {

  if (x == 6) {
    break
  }

  console.log(x)
}

In the example above, we want our loop to iterate until the counter gets to 10.

But, in the execution code, we set up an if statement to break the loop when the counter reaches 6.

When we look at the output, we can see that the numbers only print up to 5, which means the loop was successfully stopped when it reached 6.

Output:
0
1
2
3
4
5

Loop control statements: continue

The continue control statement will skip anything after the continue keyword and move to the next iteration of the loop.

Once again we can simply use the keyword wherever we want inside a loop.

Example:
for (let x: number = 0; x <= 10; x++) {

  if (x == 6) {
    continue
  }

  console.log(x)
}

In the example above, our loop will iterate until the counter gets to 10.

But, this time the if statement in the execution block tells the compiler to skip the print statement when it gets to 6, instead of completely breaking out of the loop.

When we look at the output, we can see that 6 isn’t printed to the console, which means we successfully skipped that iteration.

Output:
0
1
2
3
4
5
7
8
9
10

Summary: Points to remember

  • Iteration control allows us to repeat sections of our code by looping through them.
  • TypeScript provides us with while , do while and for loops..
  • The while loop is used when we don’t know how many times a loop will repeat.
  • The do while loop is used when we don’t know how many times a loop will repeat, but it should be at least once.
  • The for loop is used when we know how many times a loop should repeat.
  • The for loop must specify its counter and the increment/decrement of that counter in the condition block of the statement.
  • Loops can be nested inside other loops. It’s considered bad pratice to nest more than 3 levels deep.
  • The break control statement will completely break out of the loop and move on to the code below the loop.
  • The continue control statement will skip the current iteration of the loop. It will skip any code after the continue statement.