Return or console in getter method


#1

https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/getters
image
It says “Make sure you return the string and not logging it to the console.”
Here is the code:

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  get energyLevel() {
    if (typeof this._energyLevel === 'number') {
    **return** `My current energy level is ${this._energyLevel}`
    } else {
      **return** 'System malfunction: cannot retrieve energy level'
    }
  }
};

console.log(robot.energyLevel);

in exercise step 2, must I use ‘return’ instead of ‘console’?


#2

yes, because the setter method set the property (in this case _energyLevel) to the returned value of the setter. So you want to use return

setters allow you to change the behavior of properties like _energyLevel to do validation for example, like you do here


#3

don’t you mean getter ?


#4

yea, sorry, getter. When trying to access the property, you will get the value returned by the getter method