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 Setters

Jamie Moore
Jamie Moore
3,997 Points

Getters and Setters - use case examples?

I'm understanding the syntax of getters and setters, so my question is more 'why' than 'how'. I tend to learn best with some real-world examples of when these concepts are useful. Could some provide some examples of when the topics in these videos are necessary?

The example used in the video (using a setter for setting a dogs owners names) just seems like we're over complicating things. Why not just have a property called 'owner' and set the name with owner.name?

Thanks in advance!

1 Answer

Jess W
Jess W
9,490 Points

Hi there! That's a good question, I found some interesting discussions on this topic on StackOverflow. Check out this one, which is pretty much exactly your question: https://stackoverflow.com/questions/42342623/why-use-getters-and-setters-in-javascript

I also liked the chosen answer in this one, although it's not JS specific: https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors

One great reason is encapsulation of behavior associated with getting or setting the property (mentioned in those links above).