Why do I need a setter, if I am using _ to not have the property changed by others?



If I am using _ to make sure other developers know to not actively change the value of a property, why do I need a setter?


When we decide to implement setters, it is because even though we used the underscore to visually alert other developers that the property must not be changed directly, we plan to use that property dynamically (aka, we want to have it’s value changed) through the setter to modify its value indirectly and under our own conditions, that way we can make sure there is always a value being assign(not an empty value like null or an empty string), and/or it is of the type we need (ie. string). In short, we give “privatized” properties (because they are only private by developer’s code of honor, not because of JavaScript as you may recap from here) a setter when we want them to be modified in such way that we can prevent unnecessary or unexpected errors.

To clarify, let’s adjust the robot object as an example:

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  //lets give it a energy level getter
  get energyLevel () {
    return this._energyLevel;
//and since we want to have the energy level to be modified as the robot 
//performs different tasks, we will give it a setter:
  set energyLevel(numLevel) {
    if( numLevel && typeof numLevel === "Number" && numLevel > 0 ){
    // we check first if the argument is true (aka if a value has been given), and if its type is a number, and if the value is greater than 0. If all that is true, then:
      this._energyLevel = numLevel;
    } else {
      console.log( 'Error:  Value does not exist, is not a number, or not greater than zero' );

with that setter we can interact with the energy level, making sure that it is under our conditions. So, as we can see, some of the properties that we don’t want to have directly changed, we do intend to use them as mutable properties (having their values change), but we use setters as safety measure so they can be modifed under the conditions that we want.


When numLevel is zero, the first operand will yield false.


Thanks for catching it! Edited.


It will still be false when numLevel is zero. It would appear that (first) operand is not needed.