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 Setter Methods

setter()

How do I Complete this ?Also can someone help me understand the use of getters and setters.Thanks

creating_setters.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 > 60) {
            return 'Junior';
        } else if (this.credits > 30) {
            return 'Sophomore';
        } else {
            return 'Freshman';
        }
    }
  set major(p){

  }
}

var student = new Student(3.9, 60);

1 Answer

Hi Azzie!

I recently answered this question for another student.

You can see that answer here:

https://teamtreehouse.com/community/completely-confused-2

Setters and getters allow you to store and retrieve variable data with the added benefit of being able to also manipulate that data in the process.

For example, you could do some validation or store the value as all lowercase or perform some math function(s) or do some sort of formatting.

More info:

https://www.w3schools.com/js/js_object_accessors.asp

https://javascript.info/property-accessors

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set

https://www.youtube.com/watch?v=8fo-K7zRv0Y

I hope that helps.

Stay safe and happy coding!