Skip to Content
Learn
Advanced Objects
Setters

Along with getter methods, we can also create setter methods which reassign values of existing properties within an object. Let’s see an example of a setter method:

const person = { _age: 37, set age(newAge){ if (typeof newAge === 'number'){ this._age = newAge; } else { console.log('You must assign a number to age'); } } };

Notice that in the example above:

  • We can perform a check for what value is being assigned to this._age.
  • When we use the setter method, only values that are numbers will reassign this._age
  • There are different outputs depending on what values are used to reassign this._age.

Then to use the setter method:

person.age = 40; console.log(person._age); // Logs: 40 person.age = '40'; // Logs: You must assign a number to age

Setter methods like age do not need to be called with a set of parentheses. Syntactically, it looks like we’re reassigning the value of a property.

Like getter methods, there are similar advantages to using setter methods that include checking input, performing actions on properties, and displaying a clear intention for how the object is supposed to be used. Nonetheless, even with a setter method, it is still possible to directly reassign properties. For example, in the example above, we can still set ._age directly:

person._age = 'forty-five' console.log(person._age); // Prints forty-five

Instructions

1.

Currently, in robot there is a getter method for numOfSensors but no setter method! What if we need to add or remove some sensors? Let’s fix that problem.

Add a setter method named numOfSensors using the set keyword. Provide a parameter of num. Leave the function body empty for now.

2.

There are a couple of things we should do in the setter method:

  • Add a check to see if num is a number using the typeof operator.
  • num should also be greater than or equal to 0.
  • If both conditions are met, reassign this._numOfSensors to num.
3.

Now add an else that logs 'Pass in a number that is greater than or equal to 0' to the console.

4.

Use the numOfSensors setter method on robot to assign _numOfSensors to 100.

5.

To check that the setter method worked, console.log() robot.numOfSensors.

Folder Icon

Take this course for free

Already have an account?