Lesson 8 of 14 · 10 min

Objects

An object groups related values, each with a name (a key):

const phone = {
  brand: "Tecno",
  price: 180,
  colours: ["black", "blue"],
};

console.log(phone.brand);       // Tecno
phone.price = 165;              // change a value
console.log(Object.keys(phone)); // [ brand, price, colours ]

Values can be anything: numbers, strings, arrays, even other objects.

Methods

A function stored in an object is a method. Inside it, this means "the object this method belongs to":

const rectangle = {
  width: 4,
  height: 3,
  area() {
    return this.width * this.height;
  },
};

console.log(rectangle.area()); // 12

Building objects with a function

A function can return a new object each time it is called, which is a simple way to make many similar objects:

function makePoint(x, y) {
  return { x, y };   // short for { x: x, y: y }
}

Your task

Write makeStudent(name, scores). It returns an object with:

  • name and scores (an array of numbers),
  • a method average() that returns the mean of the scores,
  • a method passed() that returns true if the average is at least 50.

Then write report(students): given an array of students, return an array of the names of those who passed.

main.js
function makeStudent(name, scores) {
  return {
    // name, scores, average(), passed()
  };
}

function report(students) {
  // names of students who passed
}

const class1 = [makeStudent("Rudo", [72, 64, 90]), makeStudent("Farai", [30, 45, 52])];
console.log(report(class1));

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…