Search code examples
javascriptobjectgetter-setter

How do setters work in Javascript?


Specifically, how does it work in relation to this Codecadamy example?

let person = {
  _name: 'Lu Xun',
  _age: 137,
  set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }
    else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  }

};

It doesn't make sense to me why they put the ageIn inside of age(), what does it do?

Thanks!


Solution

  • A setter is a function that is executed whenever you are trying to change a parameter.

    set age(ageIn)
    

    In the above setter function they are trying to identify if the the parameter that they are trying to set is a number before assigning it to _age property of the object. This method is only called if user is setting value as person.age=140 and it will update person._age as 140.

    However if user is trying to update the _age property directly it will not execute this method and will directly update the person._age

    This is a useful resource to get a bit more idea about setters https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set

    Hope this helps. Happy coding