Start learning free

LESSON 205 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in TypeScript: Grades by Subject with a Record

Practice Read the full explanation

Use a dictionary, a loop, and conditionals to print each subject with its letter grade in alphabetical order.

You start with:

const grades: Record<string, number> = {"Math": 92, "English": 78, "Science": 85, "History": 67};

Build:

English: C
History: D
Math: A
Science: B

Rules:

  • Visit the subjects in alphabetical order.
  • Look up each subject's score in the dictionary and apply the grading scale (90+ A, 80s B, 70s C, 60s D, else F).
  • On each iteration print the subject, a colon and a space, then the grade, for example English: C.

Object.keys(grades).sort() gives the keys alphabetically.

const grades: Record<string, number> = {"Math": 92, "English": 78, "Science": 85, "History": 67};

const subjects: string[] = Object.keys(grades).sort();
for (const subject of subjects) {
    const score: number = grades[subject];
    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(subject + ": " + grade);
}

STEP 1 OF 10
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in TypeScript, explained

    Problem overview

    In version 5 of the Report Card project the scores are no longer in a list. They sit in an object that maps each subject name to a score: grades, typed Record<string, number>. The program prints each subject with its letter grade, one per line, in alphabetical order of the subject names.

    The scale is unchanged: 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. The starting object lists Math, English, Science and History, in that order, but the output is sorted by name:

    English: C
    History: D
    Math: A
    Science: B
    

    Approach: sort the keys, then look each one up

    An object doesn't give you "the n-th entry" by position, so the loop can't count positions as it did over arrays. The program works with the names instead. Object.keys(grades) returns an array of the object's keys, ["Math", "English", "Science", "History"], in the order they were written. Calling .sort() on that array puts the names in alphabetical order. The program then visits each name and uses it as a key to read its score.

    Sorting the names, not the object, is the point: an object's order isn't something to rely on for output. For string keys it is the order of insertion, but keys that look like integers jump to the front in ascending order. For example, Object.keys on {"b": 1, "10": 2, "a": 3, "2": 4} gives ["2", "10", "b", "a"]. Sorting the key array makes the order explicit.

    Inside the loop, each pass does what version 4 did: read the score, run the grading ladder, print one line. Only the source of the score changes, from scores[i] to grades[subject].

    For the starting data, the sorted array is ["English", "History", "Math", "Science"]. The loop reads grades["English"] first, which is 78, so the first line is a C. Then it reads History (67, a D), Math (92, an A) and Science (85, a B).

    The result is the same four lines as the expected output, because the order of the lines comes only from the order of the sorted names. The object's own order, which puts Math first, plays no part once the keys are sorted.

    Step by step

    1. Get the sorted names. Create subjects as a const of type string[], holding Object.keys(grades).sort(). The array from Object.keys is new, so sorting it doesn't touch the object.
    2. Loop over the names. for (const subject of subjects) hands out one name per pass, in the sorted order. Write the closing brace right away.
    3. Look up the score. Inside the loop, store grades[subject] in a const named score, typed number. The name is the key, and the value stored under it is that subject's score.
    4. Declare the grade. A let named grade, typed string, with no value yet.
    5. Start the ladder with if (score >= 90) for "A". The top grade is checked first, so later tests only need a lower bound.
    6. Add else if (score >= 80) for "B".
    7. Add else if (score >= 70) for "C".
    8. Add else if (score >= 60) for "D".
    9. Close with else for "F", then close the chain.
    10. Print the line inside the loop, after the chain: subject, ": " and grade, joined with +. It runs once per subject.

    The solution in TypeScript

    const grades: Record<string, number> = {"Math": 92, "English": 78, "Science": 85, "History": 67};
    
    const subjects: string[] = Object.keys(grades).sort();
    for (const subject of subjects) {
        const score: number = grades[subject];
        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(subject + ": " + grade);
    }
    

    Details worth knowing:

    • Record<string, number>. This type says "an object whose keys are strings and whose values are numbers". It is erased when the code compiles to JavaScript, where grades is an ordinary object.
    • for...of and for...in differ. for (const subject of subjects) loops over the values of an array. for (const k in grades) loops over an object's keys, but in the object's own order, not alphabetical. For the starting data it visits Math, English, Science and History.
    • Default sort() compares as text. With no comparator it orders strings by their character codes, which is fine for names but trips on numbers: [10, 9, 100, 1].sort() gives [1, 10, 100, 9]. Sorting numbers needs (x, y) => x - y.
    • sort() changes the array it is called on and returns that same array. Here it runs on the fresh array from Object.keys, so nothing else is affected.

    Edge cases and common mistakes

    • Capital letters sort before lowercase ones. The default sort compares character codes, and every capital letter has a smaller code than every lowercase one. ["Math", "english", "Art", "science"].sort() gives ["Art", "Math", "english", "science"]. With subjects named Math, English, science and Art, the lowercase one comes last. The lesson's subjects all start with a capital, so the plain sort() is enough.
    • Forgetting to sort. Without .sort() the loop follows the object's order and prints Math, English, Science, History.
    • A missing key. grades["Art"] for a subject that isn't in the object gives undefined, not an error. Looping over Object.keys avoids this, because every key it returns exists.
    • Boundaries. With Math 59, English 60, Art 80 and science 90, the output is Art: B, English: D, Math: F and science: A. The score 60 is a D and 59 an F.
    • An empty object. Object.keys({}) is an empty array, so the loop never runs and nothing is printed.

    Testing

    • The starting object prints English: C, History: D, Math: A and Science: B.
    • An object with "Math": 59, "English": 60, "science": 90, "Art": 80 prints Art: B, English: D, Math: F and science: A.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free