Setters in JavaScript


I am currently learning Setters in the JavaScript course while the exercise went ok, and everything checked green, I notice the value of the _numOfSensors didn’t change.

type or paste cconst 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){
        this._numOfSensors = num;
    } else { 'Pass in a number that is greater than or equal to 0'
  robot._numOfSensors = 100;    

I played around with the syntax, and tried it on workplace, it doesn’t log from there but if i just generally console.log(robot) i can still see 15 not 100

it would be nice to know what I am doing wrong here



The string in the else block should be logged to the console i.e. console.log('Pass in ...' );, but that is not the issue.

Steps 4 and 5 should be done outside the robot object i.e.

const robot = {
   // ....

robot.numOfSensors = 100;

You have placed these statements within the setter.

1 Like

Thank you, it worked :slight_smile:

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