Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

45 min

Nested Data and the Student Report Lab

Access optional nested data without hiding missing information

By the end of this lesson

  • Access optional nested data without hiding missing information
  • Build a small report from nested collections

Model only the structure you need

A student's record contains a name and an array of grades. An optional contact record may contain an email. What should a student with no grades contribute to an average? For this lab, no grades means no average, not zero.

const students = [
  { name: "Sara", grades: [15, 12, 18], contact: { email: "sara@example.com" } },
  { name: "Youssef", grades: [10, 9, 14] },
  { name: "Lina", grades: [] }
];
function calculateAverage(grades) {
  if (grades.length === 0) return null;
  return grades.reduce((sum, grade) => sum + grade, 0) / grades.length;
}
const report = students.map((student) => ({
  name: student.name,
  average: calculateAverage(student.grades),
  email: student.contact?.email ?? "Not supplied"
}));
console.assert(report[0].average === 15);
console.assert(report[1].average === 11);
console.assert(report[2].average === null);

Optional chaining ?. returns undefined if the immediately checked receiver is null or undefined. It does not validate a record's shape. ?? uses a fallback only for null or undefined, preserving meaningful false, 0 and empty text. Use defaults only when the policy permits them.

Guided copy warning

Copying { ...student } still shares the grades array. To modify grades in a preview, copy that array too. Avoid deeply nested structures when a simpler model represents the same need.

Independent lab

Using the report, list students whose average is at least 10, find the best student and calculate the class average. Choose and state a definition for class average before coding.

Correction

Sara and Youssef pass; Lina has no result. Sara is best. Under the policy "mean of available student averages," the class average is 13. Exclude null explicitly. Under a policy using every individual grade, results can differ when students have unequal grade counts. The data cannot choose the policy for you.

Review

This is the first version of the guided project used later. Save it with its assumptions: grades are valid numbers from 0 through 20, and students without grades are excluded from class averages. Validation and tests will strengthen this same program.

Lesson complete?

Your progress is saved on this device.