Doubt related to getters & setters

Why are getters and setters needed in Javascript ? Why can’t we just use normal code to return and assign values ?

a language offers certain features (like getters and setters), so its useful to know of its existence.

Because getters and setters allows us to modify behavior of properties:

myObj = {
  _myProp: [],
  get myProp(){
    return this._myProp.join('-');
  },
  set myProp(propIn){
    this._myProp.push(propIn);
  }
}

myObj.myProp = 5;
myObj.myProp = 6;
console.log(myObj.myProp);

as you can see in this example changes the default assign behavior and we return a string despite the property being array. This can be useful to display the output in a different to the user

furthermore, it opens up the opportunity for validation:

myObj = {
  _myProp: [],
  get myProp(){
    return this._myProp.join('-');
  },
  set myProp(propIn){
    if (this._myProp.includes(propIn)){
      console.log(`${propIn} already included in list`);
    } else {
        this._myProp.push(propIn);
    }
  }
}

myObj.myProp = 5;
myObj.myProp = 5;
console.log(myObj.myProp);

of course there are other ways to achieve the same result. Programming is always considering the pros and cons of different approaches

1 Like

In the cheatsheet for getters and setters, the statement in the getter doesn’t have a semicolon. How does this still work?

const myCat = { 
_name: 'Snickers', 
get name(){ return this._name }

we can add a semi-colon at the end of the statement:

get name() {
   return this._name;
}

although bugs can occur when semi-colon are missing in JavaScript, they are pretty rare.

JavaScript generally copes pretty well with missing semi-colons.