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 Object Interaction

Mohamad Faiz Khairi Mohd Nazri
Mohamad Faiz Khairi Mohd Nazri
5,668 Points

Why do we need the getter method for the setter method?

Hi,

since the phone method has set the property of _phone with the value that was passed as the argument when called. So why do we need the getter method to return the value of _phone property?

I also tried to remove the getter method and it seems that its still log the same things to the console.

1 Answer

Steven Parker
Steven Parker
231,236 Points

The getter allows the property to be accessed using the same name is it is set with ("phone" with no underscore).

But the getter isn't being used when you log the contents of the object, since it reports the property itself (with the underscore). But it exists for other code that might use the object.