FAQ: Advanced Objects - Setters

There is no real point to having a setter return anything since it acts on the instance variables directly and there is nothing to receive the return value.

In the above example, logging the error is the best approach. Nothing is set so you are telling the user something went wrong. We don’t want to return that message as it just goes into thin air, anyway.

1 Like

Thank you for your answer.

1 Like

const person = {
firstname: ‘Ahmed’,
lastname: ‘Anan’,
fullname(){
return ${this.firstname} ${this.lastname}

}
};

person.fullname = ‘Alex hales’
person.fullname = ‘the pianist’

console.log(person.fullname);

//prints the pianist

*If this is how I can write my code, reassign from outside why I need to use getters and setters I mean I’m so confuse why actually I need to use it.I’ve read all the ques-ans of this page searched google still can’t satisfy myself. Can anyone make me clear please.thanks *

There are going to be a million things we encounter while learning to program that will raise the same question… Why do we need this? Or, why do we need to do it this way? All kinds of why? questions surface, and that is natural. However, what is the point of going into the various reasons when all we’re learning at this stage is syntax and composition with new concepts coming at a blistering pace? Take in the rudiments and eventually the reasoning will become more evident as you begin working with the code patterns. For now, forget about why? and just learn about the way the pieces fit together.

Getter and Setter patterns have a purpose, not a raison d’être. Build one’s awareness of these patterns, how to write them and how to recognize them. The why’s and wherefore’s will be for another day.

2 Likes

Okay, have a possibly silly question but I’m just legitimately curious about this.

So, for our setter function, we provide it with the parameter of “num”. We then check if “num” is in fact a number and greater than 0, then pass it to _numOfSensors if both are true.

However, when we later go to change the actual number attached to _numOfSensors, we simply use robot._numOfSensors = 100 instead of just num… so my question is, what’s the point of the “num” parameter if we don’t use it directly to change the overall number of sensors? Is it simply to allow the setter to know it is interacting with numbers?

robot._numOfSensors = 100 bypasses the setter altogether. to use the setter, you should do:

robot.numOfSensors = 100

when we have get numOfSensors, we create a property (numOfSensors) which has a function bound to the property

so _numOfSensors is prefixed with an underscore, to prevent naming conflict with the property create by the getter, and as a convention for us developers that the property (_numOfSensors) should not used directly.

from MDN:

The set syntax binds an object property to a function to be called when there is an attempt to set that property.

so when you do:

robot.numOfSensors = 100

the property will call the underlying setter function, and pass 100 as argument for your num parameter.

Appreciate your reply!

Going back over my code, I realized I did in fact use robot.numOfSensors = 100 and simply put the underscore here as a typo. But your explanation helped me understand the purpose of the num parameter, so thank you very much! Always want to make sure I understand the concepts behind all this.

1 Like

Lesson 6. Setters

did all the steps.
after that wanted to set numOfSensors to string, so i could check what happens then.
and when i change it to string i get Pass in a number that is greater than or equal to 0 and one more line 15
why does it print 15?

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

Because your setter has a condition which must be met in order for the setting change. Otherwise it stays set at 15.

1 Like

Thanks for the Q and A. This instruction in the exercise threw me off because it says " * If both conditions are met, reassign this._numOfSensors to num ." It should say "reassign num to this._numOfSensors", right?

yes, it should :slight_smile:

1 Like

I don’t quite understand the purpose of using Getters and Setters.

I think I understand how they work but don’t really understand how they differ from creating a ‘normal’ method that updates an objects property.

The lesson on getters provides the following benefits but are these not the same when using a normal method?

Now that we’ve gone over syntax, let’s discuss some notable advantages of using getter methods:

  • Getters can perform an action on the data when getting a property.
  • Getters can return different values using conditionals.
  • In a getter, we can access the properties of the calling object using this .
  • The functionality of our code is easier for other developers to understand.

For example, this code does exactly what I want. Using a getter only allows me to envoke the method without the parenthesis right?

const person = {
  firstName: 'David',
  lastName: 'Smith',
  fullName() {
    if (this.firstName && this.lastName) {
      return `${this.firstName} ${this.lastName}`;
    } else {
      return `Error: firstname and lastname not available`;
    }
  },
  age: 34,
};

console.log(person.fullName()); // Returns 'David Smith'

// CODE ABOVE DOES WHAT THE CODE BELOW DOES, RIGHT? WHAT IS THE BENEFIT OF THE BELOW?

const person = {
  firstName: 'David',
  lastName: 'Smith',
  get fullName() {
    if (this.firstName && this.lastName) {
      return `${this.firstName} ${this.lastName}`;
    } else {
      return `Error: firstname and lastname not available`;
    }
  },
  age: 34,
};
console.log(person.fullName); // Still Returns 'David Smith'

This may be a stupid question. The correct syntax to call a getter or a setter is e.g.
object.getterName. In this exercise the getter and setter have the same name. How does this not cause confusion?

because the setter is used when doing assignment:

object.prop = 'new value';

Who-ever implemented getters and setters in javascript, was clever enough to avoid any conflict.