Can't understand getters and setters

Consider this code:

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

I have two questions:
1-If i defined the writer() method without “get” , I will simply still be able to call this method like this “lol.writer();”
What is the difference or why do I need “get”?

2-Similar to the first question , why do I need the setter , I can just change the value of the _author property like this " lol._author=‘wut’; "

1 Like

Using getters provides protection to prevent users from overwriting or changing the data in your objects accidentally. Using setters lets you provide validation logic to make sure that the data set by the user is valid for your object.

Traditionally, if you wanted to access/change a variable in an object/class (let’s call it author) you would create two methods: getAuthor() and setAuthor(args). Getters and setters basically allow for a slightly more convenient way of creating these methods. Not everyone thinks they are a good idea (for various reasons). You do not have to use them, but you should be familiar with them because you will probably run into code that does.

On a side note, currently in JS there is officially no way to make a class field private, so you can get away with lol._author=‘wut’. But the proposal is in place and in the near future you will be able to make _author private to the class and then the only way you will be able to access it is with a method or setter/getter.