DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Using getters/setters as opposed to methods?
Keff
Keff

Posted on

Using getters/setters as opposed to methods?

What are your thoughts on using getters & setters in Javascript as opposed to methods? And when and why would you use them?

This

const obj1 = {
  _name: 'Rick',
  get name(){
    return this._name;
  },
  set name(name){
    this.name = name;
  }
};
Enter fullscreen mode Exit fullscreen mode

As opposed to

const obj2 = {
  _name: 'Morty',
  getName() {
    return this._name;
  },
  setName(name){
    this.name = name;
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

I've had trouble with tsc (TypeScript compiler)'s get and set in the past, as well as I don't see much benefit.

Also the same case with Python, I see get and set as generally should be avoided, as they may obscure implementation.

The only real time I see benefit, is in Vue class components, where get will be translated to Vue getters, therefore cached.

Collapse
 
nombrekeff profile image
Keff Author

I tend to forget about them and don't use them often, can't see why. I was hoping somebody explained how they used them and why.

Collapse
 
nombrekeff profile image
Keff Author • Edited on

I don't use getters/setters often, but sometimes they make interfaces look a lot cleaner, for example: myArray.length instead of myArray.length()

Collapse
 
khrome83 profile image
Zane Milakovic

I really don’t use them. Mostly because I keep forgetting they exist.

Is there any performance reason to not use them?

Collapse
 
nombrekeff profile image
Keff Author • Edited on

I also forget about them :P

I don't think there is, although I haven't made much research in that respect.

Correction: It kinda has some side-effects and is prone to errors, for example, if a method or property is mispeled:

person.getFulName(); // Throws error
person.fulname; // Does not throw

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post