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 Getters and Setters Creating Getter Methods

Joseph Gleiter
Joseph Gleiter
4,664 Points

Bummer: It looks like your getter method is not returning a value.

this works in chrome but not in treehouse

creating_getters.js
class Student {
  constructor(gpa, credits){
      this.gpa = gpa;
      this.credits = credits;
  }

  stringGPA() {
      return this.gpa.toString();
  }

  get level(){

    if(this.credits > 90){return 'Senior';}
    else if(this.credits <= 90 && this.credits >= 61){return 'Junior';}
    else if(this.credits <= 60 && this.credits >= 31){return 'Sophomore';}
    else if(this.credits < 30){return 'Freshman';}
  }
}

const student = new Student(3.9, 8);

student.level;

2 Answers

Steven Parker
Steven Parker
229,968 Points

There's just one value for which this method returns no value, and the challenge checker just happened to try it (but you didn't when working in Chrome)! Look over your logic and see if you can spot it.

Suggestion: one way to guarantee a value is always returned is to use a plain "else" at the end instead of another "else if". And in this case, since all the other conditions cause a return, you can even omit the "else" entirely.


Spoiler: The value which is not caught by the tests when spelled out backwards is "ytriht". :wink:

Hi Joseph, this is coming a lot later than when you posted your question.

Steven's absolutely right. I just did the challenge myself. I was doing something similar, when I realised the last "else if" was not necessary.

Also, thought I'd share - because a hidden challenge was to write the conditions as simply as possible - that this could also be done using ternary operators (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator).

So, what is seen below would give the same result as using regular "if, else if, else".

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

    stringGPA() {
        return this.gpa.toString();
    }

    get level() {
      return this.credits > 90 ? 'Senior'
         : this.credits <= 90 && this.credits >= 61 ? 'Junior'
         : this.credits <= 60 && this.credits >= 31 ? 'Sophomore'
         : 'Freshman';
    }  
}

const student = new Student(3.9);