Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript Working with Classes in JavaScript Adding Methods To Our Class

Tibor Ruzinyi
Tibor Ruzinyi
17,968 Points

Which of the following is the correct code for a method that will add a course to a student’s schedule?

Can anybody explain me please how and for what reason could we use this method written in this question?

The Q was :Which of the following is the correct code for a method that will add a course to a student’s schedule?

Code :

class Student {
   constructor(gpa, courses) {
       this.gpa = gpa;
       this.courses = courses;
   }

   printGPA() {
       console.log(this.gpa);
   }
}

const ashley = new Student(3.9);

Answer:

addCourse(course){
    this.course.push(course);
  }

2 Answers

yes, confirmed, you're right. addCourse(course){this.courses.push(course);}

Steven Parker
Steven Parker
231,269 Points

It's not clear from the quiz code what a "course" is; but assuming it's just a string, an example of using the new method would be to show that the student "ashley" created in the example is taking an Algorithms course:

ashley.addCourse("Algorithms");

However, for this to work correctly, a small bug in the quiz code must be corrected in one of two ways:

// either the student creation needs a 2nd argument:
const ashley = new Student(3.9, []);

// OR the constructor needs to supply a default:
   constructor(gpa, courses=[]) {