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());