Start learning free

LESSON 105 OF 348 · FOR LOOPS - LOOPING OVER ARRAYS

Why For Loops in TypeScript: Avoiding Repeated Code

Lesson Read the full explanation

For loops are very useful for iterating over sequences of elements.

To understand the value of for loops, let’s take some time to see how frustrating our life would be if a repeated task required us to type out the same code every single time.


Example: Greeting our friends

Imagine this: We have an array of friends and we want to greet each of them using a message template.

If we only use console.log(), our program might look like this:

let friends = ["Andy", "Mircea", "David", "Mary"];

console.log("Hey, " + friends[0]);
console.log("Hey, " + friends[1]);
console.log("Hey, " + friends[2]);
console.log("Hey, " + friends[3]);

That’s ugly, but still manageable. After all, we’re writing only 4 lines of code and most probably copying and pasting a few times.

Now imagine if we had 10, 100 friends? It would take an extremely long time and by the end, we could still end up with inconsistencies and mistakes.

We’ll learn how for loops come to our rescue in the next lesson. But for now, let’s gain an appreciation for them.


Assignment
Follow the Coding Tutorial to see how frustrating our life is without for loops.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    TYPESCRIPT · FOR LOOPS - LOOPING OVER ARRAYS

    Why For Loops in TypeScript, explained

    The problem with repeating yourself

    Programs often do the same thing for every item in a collection: greet each friend, print each fruit, add up each price. Without a loop, the only tool you have is to write the statement once per item. This lesson shows how that goes, so that the for loop in the next lesson solves a problem you have felt.

    Greeting four friends

    Take an array of friends and a message that should be printed for each of them. Reading elements by index, the program looks like this:

    let friends = ["Andy", "Mircea", "David", "Mary"];
    
    console.log("Hey, " + friends[0]);
    console.log("Hey, " + friends[1]);
    console.log("Hey, " + friends[2]);
    console.log("Hey, " + friends[3]);
    

    It prints Hey, Andy, Hey, Mircea, Hey, David and Hey, Mary, one per line. For four friends this is tolerable, but it has three weaknesses that get worse as the array grows.

    • It scales badly. A hundred friends means a hundred nearly identical lines. A thousand means a thousand.
    • It breaks when the data changes. If a fifth friend is added to the array, nothing prints for them until someone writes a fifth line. If a friend is removed, the last line reads an index that no longer exists.
    • It invites mistakes. Copying and pasting a line a hundred times makes it easy to forget to change an index, or to change one in the wrong place.

    What goes wrong when the array shrinks

    The second weakness is concrete. Suppose the array has three friends, but the code still has four lines:

    let friends = ["Andy", "Mircea", "David"];
    
    console.log("Hey, " + friends[0]);
    console.log("Hey, " + friends[1]);
    console.log("Hey, " + friends[2]);
    console.log("Hey, " + friends[3]);
    

    The last line reads index 3, which doesn't exist, so the array gives back undefined and the program prints Hey, undefined. Nothing stops with an error. The code is wrong, and it still runs.

    The idea behind a loop

    In the four lines, the only thing that changes is the index: 0, 1, 2, 3. A for loop captures exactly that pattern. You write the statement once and let the loop run it for each element, so the number of lines in your program no longer depends on the number of items in the data. The loop also reads the array as it is when the program runs, which fixes the changing-data problem.

    The next lesson shows the syntax. For now, the goal is to feel what the repetition costs.

    The lesson's exercise

    The starting code declares an array of four fruits:

    const fruits: string[] = ["banana", "orange", "pear", "kiwi"];
    

    The exercise is to print "I eat FRUIT" for each fruit, one line per fruit, using only console.log and no loop. It works step by step:

    1. Pick an element by its index. Arrays count from zero, so fruits[0] is "banana" and fruits[3] is "kiwi".
    2. Join it to the text. The + operator joins strings, so "I eat " + fruits[0] gives "I eat banana". The space at the end of "I eat " is needed, since + adds nothing between the pieces.
    3. Repeat for each index. One console.log for each of the indices 0 to 3.
    const fruits: string[] = ["banana", "orange", "pear", "kiwi"];
    
    console.log("I eat " + fruits[0]);
    console.log("I eat " + fruits[1]);
    console.log("I eat " + fruits[2]);
    console.log("I eat " + fruits[3]);
    

    The output is:

    I eat banana
    I eat orange
    I eat pear
    I eat kiwi
    

    Now picture the same task for a hundred fruits, or for an array whose size isn't known until the program runs. This version can't handle the second case at all, because the number of lines is fixed when you write the code.

    Common mistakes in the repeated version

    • Starting at index 1. The first element is fruits[0]. Beginning at fruits[1] skips the banana.
    • Going one too far. With four fruits the last index is 3. Using fruits[4] prints I eat undefined.
    • Forgetting the space. "I eat" + fruits[0] prints I eatbanana.
    • Editing only some lines. If you change the message on three lines and forget the fourth, the output is inconsistent. A loop has one line, so there is one place to change.

    Key takeaways

    • Writing one statement per element repeats code, scales badly and breaks when the data changes.
    • Reading past the end of an array gives undefined, not an error.
    • A for loop runs one statement for every element, so the code stays the same size however long the array is.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free