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
173,876 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.