2

With an object defined.

var bob = {age: 10};

Defined setter as:

bob.setAge = function (newAge){
  bob.age = newAge;
};

So we can change a property as:

bob.setAge(20)

Instead of simply:

bob.age = 20;

or

bob["age"] = 20;

Is best practices the reason?

  • 1
    What are you asking? Can you share a *real* example? In this case, I don't see why you would need to create a `setAge` function. `bob.age = 20;` is fine here. If `age` was a "private" member, then you'd need a setter. – gen_Eric Jan 21 '16 at 19:51
  • So if I run `bob.age = -1`, should the program continue on as-is or would it be appropriate to throw an error? – zzzzBov Jan 21 '16 at 19:53
  • IMHO it's not a duplicate of that question, as that is very generic, but this asks specifically in case of javascript. – Gavriel Jan 21 '16 at 19:58
  • There's nothing special in JavaScript that would not make this a duplicate. – JJJ Jan 21 '16 at 20:00

2 Answers2

3

Because this allows to hide and save the state of the object against unwanted side effects

bob.setAge = function (newAge){
  bob.age = newAge || 0; // age must never be undefined or null;
};

You have to wrap everything in a module/closure/function to actually hide the fields which carry the object's state.

var user = (function () {
    var name = '';

    function getName() {
        return name;
    }

    function setName(value) {
        if (!value) {
            console.warn('setName: empty value passed');
        }
        name = value || '';
    }

    return {
        getName: getName,
        setName: setName
    };
}());

// undefined, the variable could not be resolved
console.info(user['name']);   

user.setName('Sergio Prada');
console.info(user.getName());

// warning
user.setName(null);
// empty string, undefined or null will never be returned
console.info(user.getName());
Florian Salihovic
  • 3,921
  • 2
  • 19
  • 26
1

For getters, it allows for validation checks to be applied to make sure that only correct values will ever be set.

As well as this, you can encapsulate the internal method of storage for the variable. For example, you might encrypt the data if you're storing it in the database, but decrypt in the getter so it's automatically ready

Joseph Young
  • 2,758
  • 12
  • 23