Let's put objects, arrays, functions and loops together into something genuinely useful: a program that generates report cards for a whole class.
const students = [
{ name: "Mia Garcia", scores: { math: 92, english: 85, science: 88 } },
{ name: "Omar Johnson", scores: { math: 64, english: 72, science: 58 } },
{ name: "Zoe Romero", scores: { math: 78, english: 95, science: 81 } },
];
function average(scoresObject) {
const values = Object.values(scoresObject);
let total = 0;
for (const score of values) {
total += score;
}
return total / values.length;
}
function getGrade(score) {
if (score >= 80) return "A";
if (score >= 70) return "B";
if (score >= 60) return "C";
if (score >= 50) return "D";
return "F";
}
function printReportCard(student) {
const { name, scores } = student;
console.log(`π REPORT CARD: ${name}`);
for (const subject in scores) {
const score = scores[subject];
console.log(` ${subject.padEnd(8)} ${score} (${getGrade(score)})`);
}
const avg = average(scores);
console.log(` Average: ${avg.toFixed(1)} (${getGrade(avg)})`);
console.log("");
}
for (const student of students) {
printReportCard(student);
}
// Find the top student
let top = students[0];
for (const student of students) {
if (average(student.scores) > average(top.scores)) {
top = student;
}
}
console.log(`π Top of the class: ${top.name}!`);
It prints
π REPORT CARD: Mia Garcia math 92 (A) english 85 (A) science 88 (A) Average: 88.3 (A) π REPORT CARD: Omar Johnson math 64 (C) english 72 (B) science 58 (D) Average: 64.7 (C) π REPORT CARD: Zoe Romero math 78 (B) english 95 (A) science 81 (A) Average: 84.7 (A) π Top of the class: Mia Garcia!
(padEnd(8) adds spaces to the end of each subject name until it's 8 characters long, so the scores line up neatly in a column. It's the opposite of padStart from Grade 2.)
Take a moment to look at what you just built. An array of objects, each containing a nested object, processed by small, focused functions, using loops, conditions, destructuring and template literals. This is what real code looks like. You're writing real code!
Add a fourth student to the class. Then add a new subject (maybe "history") to every student. Notice that you don't have to change any of the functions. They automatically handle the new student and the new subject. That's the power of well-organized code.
π Congratulations! You've graduated from Middle School! π
With functions, arrays and objects in your toolbox, you know the core of JavaScript. Honestly, these three ideas are 80% of what you'll use every day as a developer.
But before we let you into High School, there's something we need to talk about. Your programs are getting big enough to have serious bugs. So pack your sunscreen: it's time for Summer School.