Start learning free

LESSON 201 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in JavaScript: Grades by Subject

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 = {"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 = {"Math": 92, "English": 78, "Science": 85, "History": 67};

const subjects = Object.keys(grades).sort();
for (const subject of subjects) {
    const score = grades[subject];
    let grade;
    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

    JAVASCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in JavaScript, explained

    Problem overview

    Version 5 stores a student's scores in an object that maps each subject to its score:

    const grades = {"Math": 92, "English": 78, "Science": 85, "History": 67};
    

    The program must print each subject with its letter grade, with the subjects in alphabetical order. The scale is the familiar one: 90 and up A, 80s B, 70s C, 60s D, below 60 F. The expected output is:

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

    Approach: sort the keys, then look each one up

    An object has no position numbers, so there is no grades[0]. Instead you ask for the list of its keys, loop over that list, and use each key to look up the value. Because the order of the output matters, the key list is sorted first.

    The object's own key order is the order they were written: Math, English, Science, History. That is not alphabetical, and the lesson doesn't want to depend on it, so it builds its own sorted list. Object.keys(grades) returns the keys as an array of strings, and .sort() arranges them alphabetically, giving ["English", "History", "Math", "Science"].

    Inside the loop the grading ladder from the previous versions is unchanged: a score goes in, a letter comes out. Only the way the score is found is new.

    The loop therefore visits the subjects in this order, reading each score from the object: English (78, so C), History (67, so D), Math (92, so A) and Science (85, so B). Each visit produces exactly one printed line.

    Why not trust the object's order?

    For ordinary text keys such as these, JavaScript does keep the order in which they were added, and Object.keys follows it. Some keys break that rule: keys that look like whole numbers always come first, in ascending order, whatever order they were written in. Object.keys({b: 1, 2: 1, a: 1, 1: 1}) gives ["1", "2", "b", "a"]. An order that depends on such rules is not one to lean on when the output must be alphabetical, so the program sorts the keys itself and the order is explicit in the code.

    Step by step

    1. Create subjects. A const holds Object.keys(grades).sort(), the subject names in alphabetical order.
    2. Loop with for (const subject of subjects). This form gives you one value at a time, so there is no counter to manage. Write the closing brace at once, and put the next steps inside it.
    3. Look up the score. Inside the loop, grades[subject] reads the value stored under that key. Store it in a const named score.
    4. Declare let grade with no value, to be assigned by the ladder.
    5. Build the ladder: an if for 90 or more setting "A", then else if for 80, 70 and 60 setting "B", "C" and "D".
    6. Finish with else setting "F".
    7. Print inside the loop the subject, a colon and a space, then the grade. The loop runs four times, so four lines appear.

    The solution in JavaScript

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

    The details that matter here:

    • for...of against for...in. for (const subject of subjects) walks the values of an array. The similar-looking for (const k in grades) walks an object's keys directly, but in the order the object keeps them, so it would not give alphabetical output. Using of on the sorted array is what controls the order.
    • Square brackets look up by a variable. grades[subject] uses the value held in subject as the key. grades.subject would look for a key literally named subject and give undefined.
    • const in a for...of header. Each pass creates a fresh subject, so const is fine.
    • sort() changes the array it is called on and returns that same array. That is safe here because Object.keys already made a new array, so the object itself is untouched.
    • Default sort order. With no comparator, sort() compares strings by their character codes, so every capital letter comes before every lowercase one. ["math", "Art", "art2"] sorts to ["Art", "art2", "math"]. Numbers also sort as strings: [10, 9, 1].sort() gives [1, 10, 9]. For these subject names, which all start with a capital letter, plain sort() gives the alphabetical order the lesson wants.

    Edge cases and common mistakes

    • Relying on the object's order. Skipping the sort gives Math, English, Science, History, which is the order the object was written in, not alphabetical.
    • Using grades.subject. The dot form doesn't read the variable, so the score is undefined. Every comparison with undefined is false, and every subject comes out as an F.
    • Looking up a missing key. grades["Art"] gives undefined rather than an error. The loop only uses keys taken from the object, so this can't happen here.
    • Mixed-case names. As shown above, lowercase names sort after uppercase ones. The starter data doesn't have this problem.
    • An empty object. Object.keys({}) is an empty array, so the loop doesn't run and nothing is printed.
    • Printing outside the loop. The subject, score and grade exist only inside the loop's block.

    Testing

    • The starter data prints English: C, History: D, Math: A and Science: B.
    • {"math": 95, "Art": 50, "art2": 60} prints Art: F, art2: D and math: A.
    • {} prints nothing.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free