Javascript Objects: Getters and Setters 1


Here’s the lesson:

I’m really confused about what I missed the instructions. I tried to do this one for twenty minutes before getting the code given to me. It told me to create an empty .age setter method. Here’s my code:

set age() {


The proper solution was something that I didn’t see anywhere in the instructions. Here’s the correct way:

set age(ageIn) {


Is there a step in the instructions I missed that told me I should do that?

1 Like

A setter must always have a parameter, the new value being passed in to replace the old value.

set age(newAge) {


Whether you missed it or not cannot be determined, so moving forward make note of the comma separator, not semi-colon. We are inside the object.


Setters and getters can only exist in the context of defined attributes. That means in absence of a property, _age, set age cannot be construed. We cannot set a property age with set age.

The set and get keywords are intrinsically bound to prefixed keys of the same name. What’s more, a setter cannot exist in the absence of a getter, while the reverse remains true. A getter by itself is perfectly functional and useful when values do not change.

Getters and setters abstract away the key values they are bound to, making them less exposed to the outside. This is a layer of protection that makes code much more sound and reliable once all the wrinkles are ironed out.

Notice how we write,

instance.age = 35

That kicked in the setter which in order to resolve age needed to call the getter, which returned this._age. Now we give the setter a context, this._age, and so it can be set it to newAge.

Still wrapping my own head around this so don’t feel bad if it is confusing. Confusion is the mist above which we climb when we point ourselves upward. Oddly enough, it’s also the fuel that gets us there.


Thanks! That’s helpful. I’ll keep an eye out and use commas inside objects in the future.

Confusion describes most of my experience with learning to code so far. It’s pretty exciting, though, because every time I get confused I wind up learning something eventually. Like you said it’s an important part of growing. Every new thing I learn teaches me how much more I have yet to understand and that is super exciting to me.

1 Like