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 classes

Francisco Ortiz
Francisco Ortiz
2,667 Points

Why is this not returning the string?

Can anybody take a look at this and let me know what they are seeing that I am not?

adding_methods.js
class Student {
 constructor(gpa){
  this.gpa = gpa;
 }
 stringGPA(){
  String(this.gpa)
 } 
}
const student = new Student(3.9);
console.log(student);
stringGPA();

2 Answers

Steven Parker
Steven Parker
210,475 Points

I assume you meant to pass the value to "console.log". And since "stringGPA" is an instance method, it needs to be called on the class instance:

console.log(student.stringGPA());

Also, the method itself needs to have a "return" statement to pass back the value:

 stringGPA(){
  return String(this.gpa);  // add "return"
 } 
Vitaly Khe
Vitaly Khe
7,160 Points
console.log(student.stringGPA()) 

will return undefined..

If you expected converting gpa to a string, you have to reassign this.gpa inside your stringGpa() method. Pls note - you call stringGPA() method on instance of Student class that you have created - student

class Student {
 constructor(gpa){
  this.gpa = gpa;
 }
 stringGPA(){
  this.gpa = String(this.gpa)
 }
}
const student = new Student(3.9);
student.stringGPA();

Finally, you can check the type of student.gpa property

console.log(typeof student.gpa);
console.log("I'm Happy")