Start learning free

LESSON 204 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Report Card V4 in TypeScript: Grades for Several Students with a Loop

Practice Read the full explanation

Combine lists, loops, and conditionals to print a letter grade for each student in a class.

You start with:

const names: string[] = ["Alice", "Bob", "Carol", "Dan"];
const scores: number[] = [92, 78, 85, 67];

Build:

Alice: A
Bob: C
Carol: B
Dan: D

Rules:

  • Loop over the indices of the students (names.length) so you can read the name and the score at the same position.
  • Use the same scale as V3: 90+ A, 80-89 B, 70-79 C, 60-69 D, below 60 F.
  • On each iteration print the name, a colon and a space, then the grade, for example Alice: A.

Use a classic for (let i = 0; i < names.length; i++) and apply the grading chain inside.

const names: string[] = ["Alice", "Bob", "Carol", "Dan"];
const scores: number[] = [92, 78, 85, 67];

for (let i = 0; i < names.length; i++) {
    const score: number = scores[i];
    let grade: string;
    if (score >= 90) {
        grade = "A";
    } else if (score >= 80) {
        grade = "B";
    } else if (score >= 70) {
        grade = "C";
    } else if (score >= 60) {
        grade = "D";
    } else {
        grade = "F";
    }
    console.log(names[i] + ": " + grade);
}

STEP 1 OF 9
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Report Card V4 in TypeScript, explained

    Problem overview

    Version 4 of the Report Card project handles a whole class. Two parallel arrays describe it: names holds the students' names and scores holds their scores, and the value at position i in one belongs to the value at position i in the other. The program prints one line per student, with the name, a colon, a space and the letter grade.

    The scale is the one from the previous version: 90 or more is an A, 80 to 89 a B, 70 to 79 a C, 60 to 69 a D, and anything lower an F. For the starting data the output is:

    Alice: A
    Bob: C
    Carol: B
    Dan: D
    

    Approach: one loop, the same ladder inside

    The new idea in this version is the loop. The grading ladder is the same if / else if / else chain as before, and it now runs once for each student.

    The loop counts positions, not names. Position i reaches both names[i] and scores[i], so a counter from 0 up to names.length - 1 reads a name and its score together. That is why the loop condition is i < names.length: the last valid position is one less than the length.

    Everything about one student, the score, the grade and the printed line, belongs inside the loop body. The body starts fresh on each pass, so the variables declared there exist only for the current student.

    For the starting data the loop makes four passes:

    inamescoretest that matchesgrade
    0Alice92at least 90A
    1Bob78at least 70C
    2Carol85at least 80B
    3Dan67at least 60D

    Keeping names and scores in two arrays is simple, but it relies on discipline: the arrays must have the same length and the same order. Nothing in the language ties names[2] to scores[2]. Only the shared index does, so the program uses the same i for both reads and never sorts or edits one array without the other.

    Step by step

    1. Write the loop. A for loop with i starting at 0 and running while i < names.length, adding one each time. Write the closing brace immediately, so that everything else goes between the braces.
    2. Read the score. Inside the loop, store scores[i] in a const named score. A const is fine here, since each pass creates a new one.
    3. Declare the grade. A let named grade, typed string, with no value yet. The ladder will assign it.
    4. Start the ladder with if (score >= 90), which sets "A". Checking the top grade first means every later test needs only a lower bound.
    5. Add else if (score >= 80) for "B". It runs only when the score is below 90.
    6. Add else if (score >= 70) for "C".
    7. Add else if (score >= 60) for "D".
    8. Close with else for "F". Every score below 60 ends up here, so grade always gets a value.
    9. Print the line after the ladder but still inside the loop: names[i], ": " and grade, joined with +. Placing it inside the loop gives one line per student.

    The solution in TypeScript

    const names: string[] = ["Alice", "Bob", "Carol", "Dan"];
    const scores: number[] = [92, 78, 85, 67];
    
    for (let i = 0; i < names.length; i++) {
        const score: number = scores[i];
        let grade: string;
        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 70) {
            grade = "C";
        } else if (score >= 60) {
            grade = "D";
        } else {
            grade = "F";
        }
        console.log(names[i] + ": " + grade);
    }
    

    Details worth knowing:

    • Array types. string[] and number[] say what the arrays hold. The compiler uses them to check the code, and they are erased in the JavaScript that runs.
    • Block scope. score and grade are declared inside the loop body, so each pass gets its own pair. The i in the loop header is also local to the loop.
    • Building the line. names[i] + ": " + grade starts with a string, so every + joins text. Since the whole line is one string, the output has the form Alice: A.
    • Indexing past the end. Reading an array position that doesn't exist gives undefined and no error.

    Edge cases and common mistakes

    • <= instead of <. i <= names.length makes one extra pass with i equal to 4. Both arrays are undefined at that position, the ladder falls through to the final else, and the program prints an extra line, undefined: F, after Dan: D.
    • Arrays of different lengths. If scores has only three entries, Dan's score is undefined. Every comparison with undefined is false, so Dan gets an F: the output ends with Dan: F and no error is raised.
    • Printing outside the loop. If the console.log line sits after the closing brace, it runs once, and grade is out of scope there. The compiler reports Cannot find name 'grade', and the JavaScript that tsc still writes stops with a ReferenceError.
    • Boundaries. With the scores 90, 89, 70 and 59, the output is A, B, C and F. A score exactly on a boundary goes to the higher grade because the tests use >=.
    • Looping over the values. for (const name of names) hands out the names but not their positions, so the matching score can't be found. When two arrays line up by position, loop over the positions.

    Testing

    • The starting data prints Alice: A, Bob: C, Carol: B and Dan: D, one per line.
    • Scores [90, 89, 70, 59] print Alice: A, Bob: B, Carol: C and Dan: F.
    • Scores [92, 78, 85], one short, print Dan: F as the last line.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free