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
- Create
subjects. AconstholdsObject.keys(grades).sort(), the subject names in alphabetical order. - 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. - Look up the score. Inside the loop,
grades[subject]reads the value stored under that key. Store it in aconstnamedscore. - Declare
let gradewith no value, to be assigned by the ladder. - Build the ladder: an
iffor 90 or more setting"A", thenelse iffor 80, 70 and 60 setting"B","C"and"D". - Finish with
elsesetting"F". - 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...ofagainstfor...in.for (const subject of subjects)walks the values of an array. The similar-lookingfor (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. Usingofon the sorted array is what controls the order.- Square brackets look up by a variable.
grades[subject]uses the value held insubjectas the key.grades.subjectwould look for a key literally namedsubjectand giveundefined. constin afor...ofheader. Each pass creates a freshsubject, soconstis fine.sort()changes the array it is called on and returns that same array. That is safe here becauseObject.keysalready 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, plainsort()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 isundefined. Every comparison withundefinedis false, and every subject comes out as an F. - Looking up a missing key.
grades["Art"]givesundefinedrather 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: AandScience: B. {"math": 95, "Art": 50, "art2": 60}printsArt: F,art2: Dandmath: A.{}prints nothing.
