Getters and Setters III


Why is nothing being printed to my console? Its saying I’ve done everything right!

let person = {
_name: ‘Lu Xun’,
_age: 137,
set age(newAge){
if (typeof newAge === ‘number’){
this._age = newAge
} else {
return ‘Invalid input’

get age() {
console.log(${} is ${this.age} years old.)
person.age = ‘Thirty-nine’;
person.age = 39


Getters and Setters are internalized constructs that have a purpose across the class instance. We want our getters to be useful to any internal call to them which means we return only the object or value described by the name of the getter.

get age() {
    return this._age;

We could add a method to our object that would log a representation of its data properties.

repr() {
    return `${} is ${this.age} years old.`;



Of course this would imply setters for both _age and _name properties.

Keep in mind that getters and setters are methods, but they have some real horsepower.


Looks like we are polling the age attribute of the person object. Only thing is, the person object doesn’t have an age attrbute. Likewise if we were to poll Both of the those queries are actually method calls to their respective getters.


will work, but is uncommon. Nice of ECMA to come up with this little workaround.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.