Getters and setters 3


I’m doing exercise 14 (getters and setters III). Here’s the solution code:

let person = {
  _name: 'Lu Xun',
  _age: 137,
  set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    else {
      console.log('Invalid input');
      return 'Invalid input';
  get age() {
    console.log(`${this._name} is ${this._age} years old.`);
    return this._age;


person.age = 39;


Output is:

Lu Xun is 39 years old.

Why does “39” output as well as the sentence?
And why, if I delete the getter and write console.log(person.age); do I get “undefined”.

Why can’t it just output the number “39”?


Because you are logging the return value…

Because person.age is undefined. We need the getter to look up the _age attribute.


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