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 classes

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
229,005 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")