1

I'm working on a Codecademy course and have written the following code that works:

let person = {
  _name: 'Lu Xun',
  _age: 137,

set age (newAge) {
    if (typeof newAge === 'number'){
      this._age= newAge;
    } else {
      console.log('Invalid input');
    }
  } 
}

person.age= 22;

console.log(person['_age']);

I was getting my head around how the set works and thought that it essentially worked the same as defining a method within the person object just with different syntax.

So I tried it out, called the age method passing 22 to it from outside the object using the normal way you would call a method. It worked the same. See below.

let person = {
  _name: 'Lu Xun',
  _age: 137,

age: function (newAge) {
    if (typeof newAge === 'number'){
      this._age= newAge;
    } else {
      console.log('Invalid input');
    }
  } 
}

person.age(22);

console.log(person['_age']);

What are the benefits of using the 'set' syntax? ie why use it when a normal function/method definition works in the same way?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
rhetoric
  • 49
  • 6
  • So you can use `=` – Tavian Barnes Jun 05 '18 at 15:48
  • Why use object literals when you can assign properties to a new object one at a time? It's the same kind of question. – cdhowie Jun 05 '18 at 15:49
  • 1
    This possible duplicate should contain good information - [**JavaScript get/set methods vs. standard methods**](https://stackoverflow.com/questions/24796851/javascript-get-set-methods-vs-standard-methods) - The [**Set Documentation**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) should help too. If there is a **benefit** to use one over the other is up to you and most likely down to personal preference/primarily opinion based. – Nope Jun 05 '18 at 15:50

2 Answers2

1

Imagine you wrote a very huge code and a lot of them access a variable like this:

// The object
const person = { age: 12 }
// You access it very often
console.log(person.age);

Now you certainly want to calculate the age based on the birthdate. With a method, you would have to replace person.age with person.getAge() everywere you use it. That can take time. With getters / setters you can just replace one single line and everything keeps working.

If you don't think that this is a problem, you might wanna look at this java thread. Java doesnt have getters / setters.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • In general if you decide your property should now be calculating it's value, then a property is no longer the right use IMHO. A property should not be calling a function with possible side-effects but simply return it's current value. Would you not want to change the property to a function semantically and not rely on a hidden function call of set? In regards to making the change, seeing we are assuming a huge project, I further assume well modulated and namespaced code and unit tests in place as well as tools able to show usages and dependencies making the changes trivial, I would guess. – Nope Jun 05 '18 at 16:19
  • @nope `get age() { return (Date.now() - this.birthday) / (1000 * 60 * 60 * 24 * 365); }` is kind of pure IMO. And even though it is easy with todays IDEs to find usages that still takes time to rewrite and your commits get polluted by these changes. – Jonas Wilms Jun 05 '18 at 17:27
  • Isn't a property by definition to always return the same result each time it is called? I know behind the scenes a function is used but it is treated as a property. Anyway, neither here nor there I suppose, just talking :) +1 as solution addressed the question. In regards to refactoring, I always encourage it. It ensure no hacks or workaround artifacts are left in code but instead only tested and meaningful code is used but I know, that's personal preference. – Nope Jun 06 '18 at 10:45
0

The get/set syntax is for a property whereas using a method is just that, a method. Most of the time a simple public variable will suffice however there are times, like in your example that you want to validate the input to ensure that it meets whatever expectations you have of the value.

Also consider how your code will be called and what that will look like. If you were to use a function to change the value and a function to get the value your code will look something like this:

var myObject = new CoolObject('some parameter');
myObject.setComment('this is a super cool comment');
console.log(myObject.getComment());

Where as if you implemented the get/set functions on your property it will look like this

var myObject = new CoolObject('some parameter');
myObject.comment = 'This is a super cool comment';
console.log(myObject.comment);

At the end of the day it really doesn't matter as both code snippets will do the exact same thing however one reads easier and wont get you yelled at by your co-workers. Keep in mind the second example doesn't change if you simply expose a public variable.

Adam H
  • 1,750
  • 1
  • 9
  • 24
  • `however one reads easier and wont get you yelled at by your co-workers.` - Not really something that applies across the board and is down to personal preference and very depending on who you work with/for. – Nope Jun 05 '18 at 15:58
  • @Nope, you are right code standards do change greatly from shop to shop, I guess that is just my personal bias coming through. – Adam H Jun 05 '18 at 16:00
  • Also, setters don't work in IE with computed properties :/ – Nope Jun 05 '18 at 16:03