Start learning free

LESSON 107 OF 348 · FOR LOOPS - LOOPING OVER ARRAYS

Looping Over Arrays in TypeScript: Fixing Buggy Code I

Practice Read the full explanation

Inside the code editor we've tried to write a for loop that greets every student in the students array.

So when we ran the code, we expected it to print:

Welcome, Andy
Welcome, Sally
Welcome, John

but it seems like we made some mistakes because when we run our code, it produces errors.


Assignment:

Your task is to fix our loop such that no errors will be produced and it will print the desired output.

STEP 1 OF 1
    Ctrl + Enter to check

    TYPESCRIPT · FOR LOOPS - LOOPING OVER ARRAYS

    Buggy Code For Loops 1 in TypeScript, explained

    What the code is supposed to do

    The program has an array of three names and should greet each student on a line of their own: Welcome, Andy, Welcome, Sally and Welcome, John. The task is to fix the loop so it runs without errors and prints exactly those three lines.

    The code you start with is built from the right pieces, but they are put together wrongly:

    const students: string[] = ["Andy", "Sally", "John"];
    
    for (const name of students) {
    }
    console.log("Welcome, " + student);
    

    Two separate mistakes are hiding in these lines, and fixing only one of them still leaves a broken program.

    What goes wrong

    Mistake 1: the print is outside the loop

    A for...of loop repeats whatever sits between its curly braces, and nothing else. Here the braces are empty, so the loop does its three passes and does nothing in any of them. The console.log line comes after the closing brace, so it runs once, after the loop has finished. Even if that line worked, it could greet only once, not once per student.

    Mistake 2: the name does not match

    The loop declares a variable called name, but the message uses student. No variable with that name exists, so the program stops with an error when it reaches that line. The compiler reports it as Cannot find name 'student', and the JavaScript it still produces stops at that line with ReferenceError: student is not defined.

    There is a second reason it fails: a variable declared in the loop header with const or let exists only inside the loop. A line after the closing brace cannot see it, whatever it is called. So moving the line into the loop fixes the position problem, and the name has to be fixed as well.

    The two mistakes can hide each other. If you move the print inside the braces first, the error stays, because student is still not the loop's variable. If you fix the name first, the line still sits outside the loop and the error persists, since the variable is out of reach there.

    Fixing it step by step

    1. Choose one name for the loop variable. The task is easiest to read with student, because each pass handles one student from students. Change the loop header to for (const student of students).
    2. Move the print into the body, between the braces, so it runs on every pass.
    3. Keep the message as it is. The text "Welcome, " ends with a comma and a space, and the name is joined on with +, which gives Welcome, Andy and so on.
    4. Run it and compare the three lines with the expected output.

    The fixed code in TypeScript

    const students: string[] = ["Andy", "Sally", "John"];
    
    for (const student of students) {
        console.log("Welcome, " + student);
    }
    

    Running it prints:

    Welcome, Andy
    Welcome, Sally
    Welcome, John
    

    A few details about these lines:

    • const in a for...of header is fine. Each pass creates a fresh variable and gives it the next element, so nothing is reassigned. let would work too; use const when the body never changes the variable.
    • for...of gives values, not positions. student is the string itself, not an index into the array.
    • The type annotation is optional. string[] says the array holds strings. TypeScript would infer it from the literal, and the annotation disappears when the code is compiled to JavaScript.
    • Either name works. Keeping the loop variable name and printing name is equally correct. What matters is that the header and the body use the same word.
    • Template literals are an alternative. console.log(`Welcome, ${student}`) prints the same text.

    Common mistakes

    • Fixing the name but not the position. The error message stays the same, which makes it look as if nothing changed. Check both the name and where the line sits.
    • Misplaced braces. Putting {} after the header and the print below, or closing the loop before the print, brings back the original problem.
    • Typing the name differently. TypeScript names are case-sensitive, so Student and student are different variables, and students is the whole array. Printing students would show the array's contents instead of one name.
    • Forgetting the space. "Welcome," without the trailing space prints Welcome,Andy.

    Checking your fix

    Change the code in the editor above and run it. There should be no error message, and the output should be exactly three lines, one per student, in the order of the array. If you see the same line three times, or a single line, look again at the loop header and the body.

    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free