JavaScript

michael conour
michael conour
4,438 Points

Solution. Want feedback

This is my solution. Is there more of a streamlined approach someone might be willing to offer?

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 {
      return 'Freshman'
    }
  }

}

const student = new Student(3.9);

console.log(student.level);
tapio
tapio
13,751 Points

It looks good to me. You could simplify it a little bit though. Since else if statements are only executed if the previous condition hasn't been met you could go with something like that:

get level() {
      if(this.credits > 90) {return 'Senior'}
    else if (this.credits > 60) {return 'Junior'}
    else if (this.credits > 30) {return 'Sophomore'}
    else {return 'Freshman'}
  }

2 Answers

Steven Parker
Steven Parker
187,496 Points

Some very minor compacting tricks:

  • you only need to test conditions not eliminated by previous tests
  • braces can be omitted from single statements
  • a final "else" is not needed if all other conditions end with "return"
  get level() {
    if (this.credits > 90) return 'Senior';
    else if (this.credits > 60) return 'Junior';
    else if (this.credits > 30) return 'Sophomore';
    return 'Freshman';
  }
michael conour
michael conour
4,438 Points

Thank you both. Very helpful!