Search code examples
javascriptobjectpropertiesvariable-declaration

JavaScript - Is it okay to define a property of a previously declared object during a variable declaration?


Is it common practice (or at least syntactically valid across browsers and implementations of JS) to abuse RTL associativity of assignment operators so that one can define two variables (with the first being an object) so that the second is assigned to a (newly) named property of that object which is itself assigned to another value, so that a SyntaxError() is not generated?

I know that sounds complicated, but here is the code:

var x = {}, y = x.l = 9; // generates no errors
console.log(x.l, y); // 9 9

Since:

var t = {}, t.l = 9; // Syntax Error, no doubt because t is already defined

Solution

  • The line:

    var x = {}, y = x.l = 9;
    

    effectively becomes:

    var x = {};
    var y = x.l = 9;
    

    which is processed as:

    // Parse phase
    var x; // assigned the value undefined
    var y; // assigned the value undefined
    
    // Execution phase
    x = {};
    x.l = 9;
    y = x.l;
    

    Noting that in an assignment expression, the value on the right is assigned to the expression on the left. Compound assignments are evaluated left to right, but assigned from right to left, hence x.l = 9 is assigned before y = x.l, even though it's on the right.

    Now try that with the second example:

    var t = {}, t.l = 9;
    

    becomes:

    // Parse phase
    var t;   // assigned the value undefined
    var t.l; // syntax error, stop
    

    The var keyword at the start of a statement means the next thing must be a valid identifier. t.l is not a valid identifier (it can only be interpreted as an identifier followed by a dot property accessor), so that's it. Everything stops.