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

sergio Roma
sergio Roma
6,642 Points

getter level

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

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

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

    }

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

const student = new Student(3.9, 30);
console.log( student.level ); 

1 Answer

Steven Parker
Steven Parker
231,275 Points

Oddly, someone had this same exact issue just yesterday.

You have the right idea, but this code will not return a value in all cases. In particular, what if the "credits" were 30, 60, 61, or 90? The ranges need to be extended to cover those possibilities also.

Coding tips:

  • When using an "else if" chain, I always like to have the last item be just a plain "else" to guarantee that nothing will "slip through" (though you might still need to adjust things to insure the correct things are done).
  • You can simplify tests by not re-testing conditions from the previous steps in the chain. For example, after testing for items with a value over 90, it's not necessary to check for less than or equal to 90 in the next test, since you know that condition must be true for it to have skipped the previous stage.