Advanced objects: getters and setters

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  _numOfSensors: 15,
  get numOfSensors() {
    if(typeof this._numOfSensors === 'number'){
      return this._numOfSensors;
    } else {
      return 'Sensors are currently down.'
    }
  },
  set numOfSensors(num) {
    if(typeof num === 'number' && num >= 0) {
      return this._numOfSensors = num;
    } else {
      return 'Pass in a number that is greater than or equal to 0';
    }
  }
};


robot.numOfSensors = 'high';
console.log(robot.numOfSensors);

Hello, can anyone help me, please?
Why does it still log 15 in the console instead of an error?

1 Like

Because you’re not passing a number to your setter, the setter doesn’t change the _numOfSensors property.
So it’s still 15, as set inside your object.

Essentially the string ‘high’ has been rejected by your setter. Which is correct.

But setters don’t return anything, so you’re not seeing the error message you’ve set in your setter’s else condition. So that would be better being

console.log( 'Pass in a number that is greater than or equal to 0');

Then you’d see your error message when you do

robot.numOfSensors = 'high';
2 Likes

And then to test the error condition in your getter, you change the value of _numOfSensors directly, before you console.log the property.

  set numOfSensors(num) {
    if(typeof num === 'number' && num >= 0) {
      **return** this._numOfSensors = num;
    } else {
      **return** 'Pass in a number that is greater than or equal to 0';
    }
  }

Setters are not intended to return values. They set properties. As a rule you should never use return in a setter. As @antonjw pointed out, you should use a console.log to print the error message to the console. The return in your return this._numOfSensors = num; is unnecessary, and isn’t doing anything. Hopefully this helps.

2 Likes