Use dot notation inside of a console.log() to get the value saved to your _age property and print it to the console


#1

Can you check and see why I get ‘undefined’ when I try to print out _age property.

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;
console.log(person.age);

#2

because the get age() method returns undefined, because you use an empty return keyword.


#3

What is the empty return keyword? I don’t know what that is. Can you show me where I’ve done that in the program. Thanks.


#4

There is a line break after return so nothing is sent back to the caller.

Your code, made reader friendly:

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;
console.log(person.age);

Note that I’ve corrected the return statement.


Commentary

In a purist world, the getter for this property would return a single value and not log anything. What you have is okay, but what if our program wants just that piece of information, without verbosity? If the method logs everytime it is called, we don’t have that flexibility in the design.

  get age () {
    return this._age;
  }

Out in the wild we could write,

console.log(`${person.name} is ${person.age} years old.`);

In my view, and for good reason, it would be better for this method to return nothing. Setters do not normally return anything so this goes against that grain, for starters. The user is made aware of the error when it is logged. Nothing need be sent back to the caller as it will not be evaluated. It’s unexpected.

What will be seen by the caller is nothing, which is conveyed in the response if we poll it.

console.log(person.age = `forty`)
// Invalid input
// <- Invalid input

Remove the return statement,

console.log(person.age = `forty`)
// Invalid input
// <- undefined