Start learning free

LESSON 119 OF 348 · WHILE LOOPS & FOR LOOPS

The Classic for Loop in TypeScript

Lesson Read the full explanation

There is a more powerful way to use the for loop in TypeScript.

For loops can be declared with three optional expressions separated by semicolons:

for (initialization; condition; iteration) {
	instruction1;
	instruction2;
	...
}

Let's break down each component:

  • The initialization statement is executed one time only before the loop starts and is typically used to define and set up the iterator variable.

  • The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true. When the condition is false at the start of the iteration, the loop will stop executing.

  • The iteration statement is executed at the end of each loop iteration, prior to the next condition check and is usually used to update the iterator variable.


Example:

for (let i = 0; i < 4; i++) {
	console.log("Hello world!");
}

// This code prints "Hello world!" on four different lines

Let's break down this code:

  • The initialization statement is let i = 0. We create and initialize the iterator variable i so the loop starts counting from 0.

  • The condition statement is i < 4, meaning the loop will run as long as the iterator variable, i, is less than 4.

  • The iteration statement is i++. This means that after each iteration, after running the code inside {}, i will get increased by 1.


This is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 4 true? <=> Is 0 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 1
	
2. Second iteration:
	a. Is i < 4 true? <=> Is 1 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 2
	
3. Third iteration:
	a. Is i < 4 true? <=> Is 2 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 3
	
4. Forth iteration:
	a. Is i < 4 true? <=> Is 3 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 4

5. Fifth iteration:
	a. Is i < 4 true? <=> Is 4 < 4 true? No.
	b. Exit the loop.

Assignment

Let's print "I promise to learn coding." 5 times using a for loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · WHILE LOOPS & FOR LOOPS

    The For Loop in TypeScript, explained

    What the for loop is for

    Counting loops written with while need the starting value, the condition and the update in three different places. The classic for loop puts all three in the header, on one line, so you can see at a glance how the loop starts, when it continues and how it moves. That is why it is the usual choice when you know how many times to repeat something, or when you walk through a range of numbers.

    The syntax

    for (initialization; condition; iteration) {
        // statements to repeat
    }
    

    The three parts, separated by semicolons, run at different moments:

    • Initialization runs once, before anything else. It usually declares the loop variable.
    • Condition is checked before every pass, the first one included. When it is true, the body runs. When it is false, the loop ends.
    • Iteration runs after every pass of the body, then the condition is checked again. It usually moves the loop variable.

    Tracing a loop

    Here is a loop that prints a message four times:

    for (let i = 0; i < 4; i++) {
        console.log("Hello world!");
    }
    

    The order of events is:

    1. let i = 0 creates the variable, once.
    2. Is 0 < 4? Yes. Run the body, then i++ makes i equal to 1.
    3. Is 1 < 4? Yes. Run the body, then i becomes 2.
    4. Is 2 < 4? Yes. Run the body, then i becomes 3.
    5. Is 3 < 4? Yes. Run the body, then i becomes 4.
    6. Is 4 < 4? No. The loop ends.

    The body ran for i equal to 0, 1, 2 and 3, which is four times. Starting at 0 and using i < n is the standard way to repeat something exactly n times, and the same shape appears again whenever you loop over the positions of an array.

    TypeScript details

    • let keeps the variable inside the loop. A variable declared with let in the header exists only for the loop. Reading i after the closing brace is a compile error: the compiler reports that it cannot find the name i.
    • The type is inferred. In let i = 0 the compiler knows that i is a number, so you do not have to write let i: number = 0. Both are correct.
    • i++ means "add 1 to i". It is the usual way to write the update. i += 1 does the same.
    • Every part is optional. You may leave a part empty, but the semicolons must stay. A header written as for (;;) has no condition, which counts as always true, and it loops until a break or a return stops it.

    The exercise

    The task is to print "I promise to learn coding." five times. The message is the same on every pass, so the loop variable only has to make the body run five times. The two steps are:

    1. Write the loop header. Start i at 0, continue while i < 5, and add 1 after each pass. The values of i are 0, 1, 2, 3 and 4, which is five values.
    2. Put the print statement in the body. console.log with the message runs once per pass, so the message appears five times, each on its own line.

    The solution in TypeScript

    for (let i = 0; i < 5; i++) {
        console.log("I promise to learn coding.");
    }
    

    The loop variable i is not used inside the body. It is there only to count the passes, and that is perfectly normal.

    Common mistakes

    • Commas instead of semicolons. The three parts of the header are separated by semicolons. for (let i = 0, i < 5, i++) does not compile.
    • Off by one. Writing i <= 5 with a start of 0 prints six times, and i < 4 prints four times. To repeat five times from 0, use i < 5.
    • A condition that is never false. Writing i > 0 with i++ from 0 gives a loop that runs 0 times. Writing i >= 0 with i++ gives a loop that never ends. Read the header aloud: "start at 0, keep going while i is below 5, add 1 each time."
    • A semicolon after the header. for (...); makes an empty loop, and the block below it then runs once, outside the loop.
    • Changing i inside the body. The iteration step still runs afterwards, so extra changes make the count hard to follow and can cause infinite loops.

    Key takeaways

    • A for header holds the initialization, the condition and the iteration, separated by semicolons.
    • Initialization runs once, the condition runs before each pass, and the iteration runs after each pass.
    • for (let i = 0; i < n; i++) runs its body exactly n times.
    • A variable declared with let in the header cannot be used after the loop.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free