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!

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


Francesco Paolini
Francesco Paolini
9,910 Points

understanding getters and setters

maybe it's just because i didn't made enough practice with OOJS, but i think i don't understand what getters and setters are used for. I would like a practical explanation of why they are used in a real life situation please

1 Answer

Steven Parker
Steven Parker
228,001 Points

Some common benefits of using accessor methods (getters and setters):

  • it gives simpler syntax
  • it allows equal syntax for properties and methods
  • it can secure better data quality
  • it is useful for doing things behind-the-scenes

And a code example:

var person = {
  firstName: "John",
  lastName : "Doe",
  get fullName() {
    return `${this.firstName} ${this.lastName}`;

The object here stores only first and last names, but the getter provides access to the full name, with the same syntax as a property, and combining the other properties "behind-the-scenes".