Snippets Collections
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){
      this._numOfSensors = num;
    } else {
      console.log('Pass in a number that is greater than or equal to 0')
    }   
  } 
};

robot.numOfSensors = 100;
console.log(robot.numOfSensors);
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)
star

Tue Oct 05 2021 16:17:03 GMT+0000 (Coordinated Universal Time) https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/setters

#javascript #objects #advancedobjects #setters #if
star

Tue Oct 05 2021 16:09:40 GMT+0000 (Coordinated Universal Time) https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/getters

#javascript #objects #getters #advancedobjects

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension