Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

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
216,135 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".