Start learning free

LESSON 115 OF 348 · WHILE LOOPS & FOR LOOPS

The While Loop in TypeScript: Syntax, Flow and a Counter

Lesson Read the full explanation

A while loop allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

while(condition) {
	instruction1
	instruction2
	...
}

Let's check an example:

let count = 1;
while(count <= 5) {
	console.log("I made a mistake");
	count++;
}
console.log("Finished!");

The output of this program is:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

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

0. Creates and initializes a variable count = 1

1. First iteration:
	a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes. 
	b. console.log("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 2
	
2. Second iteration:
	a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes. 
	b. console.log("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 3
	
3. Third iteration:
	a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes. 
	b. console.log("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 4
	
4. Forth iteration:
	a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes. 
	b. console.log("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 5

5. Fifth iteration:
	a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes. 
	b. console.log("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 6
	
6. Sixth iteration:
	a. Is count <= 5 true? <=> Is 6 <= 5 true? No. 
	b. Terminate the loop.

	
7. console.log("Finished!"); => Output: Finished!

Pro Tip:

A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.


Assignment

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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    TYPESCRIPT · WHILE LOOPS & FOR LOOPS

    The While Loop in TypeScript, explained

    What a while loop does

    A while loop repeats a block of statements for as long as a condition is true. Before every pass, the program evaluates the condition. If it is true, the body runs once and the program evaluates the condition again. If it is false, the loop ends and the program continues with the first statement after the closing brace.

    The structure looks like this:

    while (condition) {
        instruction1;
        instruction2;
    }
    

    You can think of it as an if statement that jumps back and asks its question again after the body.

    A worked example

    let count = 1;
    while (count <= 3) {
        console.log("I made a mistake");
        count++;
    }
    console.log("Finished!");
    

    This prints:

    I made a mistake
    I made a mistake
    I made a mistake
    Finished!
    

    The trace below shows what happens, with the loop limited to three passes:

    1. count is created with the value 1.
    2. Is 1 <= 3? Yes. Print the message. count++ makes it 2.
    3. Is 2 <= 3? Yes. Print the message. count becomes 3.
    4. Is 3 <= 3? Yes. Print the message. count becomes 4.
    5. Is 4 <= 3? No. The loop ends.
    6. The program prints Finished!, once.

    The condition is checked one more time than the body runs. Three passes need four checks, and the last check is the one that fails.

    The three parts every counting loop needs

    • Initialization. A variable declared before the loop, such as let counter: number = 1;. Use let, because its value will change.
    • Condition. The expression in the parentheses, such as counter <= 5. It decides whether another pass happens.
    • Update. A statement in the body that moves the variable toward making the condition false, such as counter++, which adds 1.

    If the update is missing, the condition never changes, and the loop never ends. This is an infinite loop.

    A condition can be false from the start

    If the condition is false the first time it is checked, the body never runs at all:

    let n: number = 10;
    while (n < 5) {
        console.log("never printed");
    }
    console.log("skipped, n is", n);
    
    skipped, n is 10
    

    The exercise

    The task is to print I promise to learn coding. five times, this time with a loop instead of five copies. The lesson builds it in four steps:

    1. Declare the counter. let counter: number = 1;. The : number annotation states the type; TypeScript would infer it anyway. It must be let, since the loop changes it.
    2. Write the loop with its condition. while (counter <= 5) is true for the values 1, 2, 3, 4 and 5, which gives five passes.
    3. Print inside the body. One console.log with the sentence.
    4. Update the counter. counter++ inside the body. Without it, counter stays 1 and the loop prints forever.
    let counter: number = 1;
    while (counter <= 5) {
        console.log("I promise to learn coding.");
        counter++;
    }
    

    After the fifth pass, counter is 6, the condition 6 <= 5 is false, and the loop ends.

    Tracing the exercise

    Writing down the value of the counter at the moment of each check is the quickest way to find an off-by-one error. For the loop above, the checks go like this:

    Checkcountercounter <= 5Result
    1st1trueprint, counter becomes 2
    2nd2trueprint, counter becomes 3
    3rd3trueprint, counter becomes 4
    4th4trueprint, counter becomes 5
    5th5trueprint, counter becomes 6
    6th6falseloop ends

    Five true checks give five lines of output. This is why the number you compare against, here 5, is also the number of repetitions when the counter starts at 1 and the condition uses <=.

    Common mistakes

    • Forgetting the update. The classic bug: the program never finishes.
    • Off-by-one conditions. Starting at 1 with < 5 gives four passes, and starting at 0 with <= 5 gives six. Count the values the counter takes.
    • Using const for the counter. counter++ then fails. The compiler reports that it cannot assign to a constant, and at run time the JavaScript throws a TypeError.
    • Putting the update outside the braces. It then runs after the loop, which is never reached.
    • A semicolon after the header. while (counter <= 5); makes the semicolon the loop's whole body. That body is empty and changes nothing, so the loop never ends, and the braces below it are only a separate block.

    Key takeaways

    • while (condition) { ... } repeats its body as long as the condition is true, checking before every pass.
    • A counting loop needs a starting value, a condition and an update.
    • If the condition starts false, the body never runs.
    • Always make sure something in the loop moves the condition toward false.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free