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

If you wanted to add some validation later, it is possible via the setter. Also, it allows you to have private variables which can interact with the values you may set.

1 Like

An example:

class Wine {
  constructor(brand, age) {
    this.validate(brand, 'string');
    this._brand = brand;
    this.validate(age, 'number');
    this._age = age;
  }
  
  validate(val, type) {
    if (typeof val !== type) {
      throw new Error(val + ' should be a number');
    }
    if (type === 'string' && !val.length) {
      throw new Error(val + ' should not be an empty string')
    }
  }
  // getters
  get brand() {
    return this._brand;
  }
  get age() {
    return this._age + ' years old';
  }

  // setters
  set brand(val) {
    this.validate(val, 'string');
        this._brand = val;
  }
  set age(val) {
    this.validate(val, 'number');
    this._age = val;
  }
}
//the lesson's example
const myWine = new Wine('Yellow Tail', 40);
console.log(myWine.brand); // 'Yellow Tail'
console.log(myWine.age);  // '40 years old'
myWine.age = 50;
console.log(myWine.age); // '50 years old'
myWine.age = '51'; // Error: 51 should be a number
myWine.brand = '';  // Error:  should not be an empty string
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.