Could calling a setter method be mistaken as reassigning a property?

https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/setters

robot.numOfSensors = 100;

This code calls the setter method numOfSensors on robot to reassign numOfSensors to 100. Would there ever be a case where let’s say the code runs and it changes numOfSensors directly instead of using the setter method?

The only way to edit the property directly without the setter would be by using the exact property name. So if both the property and the setter are called numOfSensors then yes this would cause that conflict. However as long as you remember to use the _ at the beginning of property names then it should never become an issue.

Ok thanks for this. Two more questions though, do getters and setters need to be used together? And what is really the purpose of a getter?

They don’t need to be used together, technically they’re not required however it’s good practise and they do have benefits. Getters have the same benefit as setters in that you can apply validation. Setters will check the user input and make sure it’s what you want before adding it, however what if there’s an error somewhere in the code that changes the property directly? The getter can have similar validation put on it to return a specific error message to the console if the property doesn’t have the type of data you want in it. Therefore you know the source of the issue and can find out where the problem is coming from.

A getter I would say has less direct benefits than a setter as ideally the property will not be changed without the setter, thus your validation should hold. However it’s still worth having so that you can use the same call whether you’re getting or setting a value eg. robot.numOfSensors is a getter, robot.numOfSensors = 100 is a setter.

1 Like

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