Search code examples
javascriptexpressionvariable-assignmentgetter-setter

What does a return statement do inside a setter?


I have the following code:

var o = {};
o.a = 1;

var _value = 1;
Object.defineProperty(o,"a",{
    set: function(value){
        _value = value + 1;
        console.log("log: ", value, _value);
        return _value;
    },
    get: function(){
        return _value;
    }
});

In the setter method, I increment _value by one before returning it. So if I set o.a = 5, I would expect the console to print 6 (even though I realize that returning a value from setter doesn't make sense, usually). However, as the following snippet shows, the console prints 5:

> o.a = 5;
log: 5 6 // from console.log;
5 // return; why does it == value and not value + 1?
> o.a;
6
> var i = o.a = 5;
> i;
5
> o.a;
6

So my question is why does it return 5 and not 6?

I hope this is not because I made some silly mistake in the code.


Solution

  • Lets look at the simple assignment:

    11.13.1 Simple Assignment ( = )

    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).

    So rval is assigned the value that is going to be assigned to left hand side (o.a). In your case 5.

    1. Throw a SyntaxError exception if the following conditions are all true: [...]
    2. Call PutValue(lref, rval).

    This is where the value is assigned to the left hand side (PutValue(o.a, 5)). As you can see, nothing is done with whathever PutValue returns (it doesn't return anything).

    1. Return rval.

    It simple returns the value that was assigned, in your case 5.


    The assignment expression always returns the value that was assigned.