Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Tibor Ruzinyi
Tibor Ruzinyi
16,582 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

Steven Parker
Steven Parker
210,456 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=[]) {

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