Advanced Objects - setters

Hi, I want to ask about specifically exercise 4 of this setter section ( Use the numOfSensors setter method on robot to assign _numOfSensors to 100).

Can you elaborate more on why the answer is robot.numOfSensors = 100 and NOT robot._numOfSensors = 100 (with the underscore) when using the setter method? The lession did not explain about this part, so I am a little uncertain about how to the setter method to re-assign new values. Thanks.

1 Like

Oftentimes when we’re using Javascript objects, we don’t want people just going in and changing the properties to whatever they want, as this is how we end up with broken code. So it’s become standard practise to use the _ at the beginning of the property to signify that we don’t want that value changed directly.

However sometimes you do want that value to be changed to specific values, hence you create a setter method. This setter method is typically the same wording as the property just without the underscore, hence us having the property _numOfSensors vs the setter numOfSensors. If we didn’t use the underscore, then people would try to use the setter and instead directly change the value of the property, bypassing all our built in validation to prevent this.

Therefore by keeping them different, you use the setter method to set the value i.e., robot.numOfSensors = 100, and that way we can make sure that the user follows our validation rules, in this case making sure it is a positive integer.

TL;DR: using robot.numOfSensors instead of robot._numOfSensors allows us to add validation, ensuring that the property is not changed to an invalid value e.g, robot._numOfSensors = "hello" works, robot.numOfSensors = "hello" will not.