Getter ands setter functions

Tell us what’s happening:
I am not sure I really understood the function of getter & setter functions.
I feel I am missing an important point…
The example given is as below :

class Book {
  constructor(author) {
    this._author = author;
  }
  // getter
  get writer() {
    return this._author;
  }
  // setter
  set writer(updatedAuthor) {
    this._author = updatedAuthor;
  }
}
const lol = new Book('anonymous');
console.log(lol.writer);  // anonymous
lol.writer = 'wut';
console.log(lol.writer);  // wut

While I can reach and manipulate the class variables with below code :

Your code so far



class Book {
constructor(author) {
  this._author = author;
}

}
const lol = new Book('anonymous');
console.log(lol._author);  // anonymous
lol._author = 'wut';
console.log(lol._author);  // wut

Having this, why do we need the getter and setter functions?
Thank you for your help.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36.

Challenge: Use getters and setters to Control Access to an Object

Link to the challenge:

1 Like

getters and setters are used when using private variable.

in your code there are no private variables so it does not matter whether you use getters and setters or not

1 Like

Now it fits!!! This means, if the “_author” variable was private and couldn’t be reached by the calling function, then we would have to define the getter and setter function to manipulate and read the variable.
In our case, since the “_author” can be reached from the caller function we don’t need it.
Thank you so much!

getters and setters are called accessor properties, i.e. they allow you access to object properties “through” them, so you don’t have to handle them directly.

One can still change object properties from outside, the underscore is just to show that it should not be touched outside object. Using setter here offers a better way to set a property.

Also, using accessor properties one can use extra logic while dealing with properties.

Take the following example:

var forum = {
  forename: "free",
  surname: "CodeCamp",

If we want to get the fullname, we can do so through a getter:

var forum = {
  forename: "free",
  surname: "CodeCamp",

  get fullName() {
    return `Full name of the user is ${this.forename}${this.surname}`;
  }
}

And now:

forum.fullName // Output: Full name of the user is freeCodeCamp

We can also set a fullName property, but it won’t actually change the object:

set fullname(fullNameValue) {
    [this.forename, this.surname] = fullNameValue.split(" ")
  }

Hence your “private” variables won’t be changed outside the object.

NOTE: getters and setters aren’t invoked like a function, they are called just like a property.

1 Like