What is the point of getters and setters if you can access the object's properties directly?

Tell us what’s happening:

I don’t get the point of getters and setters, I mean what the point of setters and setters if we can access the properties directly?

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

//my example
const dogy = new Book('about dogs');
console.log(dogy.writer);  // abut dogs
dogy.writer = 'woof';
console.log(dogy.writer);  // woof

Your browser information:

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

Link to the challenge:
I can’t include links yet but you can check this path
//https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object

It’s a very common pattern in OOP languages like Java because most of times you want to keep your variables private. This is where getter and setter comes in so that you can’t directly modify the variables inside constructors.

IMHO, it is less useful to have setters and getters in JavaScript. Here is an article I found that lists its advantages. Although it seems controversial according to one of its comments.

1 Like

actually, I have a little Java background, and getters and setters were kindly surprising especially they

Notice the syntax we are using to invoke the getter and setter - as if they are not even functions.