Question

JavaScript setter updates the internal value at the reference but the return value is not correct.

var Game = 
{   
    get points() {
        return this._points;
},

    set points(x){        
       x = Math.min(x,25);

       this._points = x;   
       return this._points;
    }
};

Game.points = 10 ;

console.log(Game.points); // outputs 10

var updatedPoints = (Game.points = 60);

console.log(updatedPoints); // outputs 60
console.log(Game.points); // outputs 25

Expected value for 'updatedPoints' was 25 !

Any idea why this could be happening ? Can you suggest if there is a way to fix this ?

Reason to fix this: To make sure the JS code performs as expected , maintainibility !

Was it helpful?

Solution

The JavaScript simple assignement (=) returns the right value as per the specification (11.13.1). This behavior ignores whatever validation happens in your setter.

From the spec:

The production AssignmentExpression : LeftHandSideExpression = AssignmentExpression is evaluated as follows:

  1. Let lref be the result of evaluating LeftHandSideExpression.
  2. Let rref be the result of evaluating AssignmentExpression.
  3. Let rval be GetValue(rref).
  4. Throw a SyntaxError exception if the following conditions are all true:
    • Type(lref) is Reference is true
    • IsStrictReference(lref) is true
    • Type(GetBase(lref)) is Environment Record
    • GetReferencedName(lref) is either "eval" or "arguments"
  5. Call PutValue(lref, rval).
  6. Return rval.

So there is no way to "fix" your issue as it is by design. Checking Game.points should be enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top