15

I understand that the assignment operator is right associative.

So for example x = y = z = 2 is equivalent to (x = (y = (z = 2)))

That being the case, I tried the following:

foo.x = foo = {a:1}

I expected that the object foo would be created with value {a:1} and then the property x will be created on foo which will just be a reference to the foo object.

(This is actually what happens if I was to separate the multiple assignment statement into two separate statements foo = {a:1};foo.x = foo; )

The outcome was actually:

ReferenceError: foo is not defined(…)

So then I tried the following:

var foo = {};
foo.x = foo = {a:1};

Now I don't get the exception anymore but foo.x is undefined!

Why is the assignment not working as I expected?


Disclaimer: The 'duplicate' question seems to be very different to the one that I'm asking, as the issue there is that the variables that were created in the assignment were global, as apposed to variables created with the var keyword. That's not the issue here.
Danield
  • 121,619
  • 37
  • 226
  • 255

3 Answers3

11

There's an important difference between associativity and order of evaluation.

In JavaScript, even though the assignment operator groups right to left, the operands are evaluated left to right before the actual assignments are performed (which do occur right to left). Consider this example:

var a = {};
var b = {};
var c = a;

c.x = (function() { c = b; return 1; })();

The variable c initially references a, but the right-hand side of the assignment sets c to b. Which property gets assigned, a.x or b.x? The answer is a.x because the left-hand side is evaluated first, when c still references a.

In general, the expression x = y is evaluated as follows:

  1. Evaluate x and remember the result.
  2. Evaluate y and remember the result.
  3. Assign the result from step 2 to the result of step 1 (and return the former as the result of the expression x = y).

What happens with multiple assignments, as in x = (y = z)? Recurse!

  1. Evaluate x and remember the result.
  2. Evaluate y = z and remember the result. To do this:
    1. Evaluate y and remember the result.
    2. Evaluate z and remember the result.
    3. Assign the result from step 2.2 to the result of step 2.1 (and return the former as the result of the expression y = z).
  3. Assign the result from step 2 to the result of step 1 (and return the former as the result of the expression x = (y = z)).

Now let's look at your example, slightly edited:

var foo = {};
var bar = foo;         // save a reference to foo
foo.x = (foo = {a:1}); // add parentheses for clarity

foo.x is evaluated before foo gets assigned to {a:1}, so the x property gets added to the original {} object (which you can verify by examining bar).

Michael Liu
  • 52,147
  • 13
  • 117
  • 150
  • Thanks for this great explanation, but I still don't fully follow. I understand that the expression on the left like `c.x` or `foo.x` will be evaluated *first*, however, why isn't it *later assigned* with the return value of the function (=1) or with foo={a:1} in my example....like you yourself explain in step 3? – Danield Dec 02 '15 at 12:11
  • `foo.x` **is** indeed set to the result of `foo = {a:1}`. The question is, which object actually gets updated—`{}` or `{a:1}`? In the steps for evaluating `x = (y = z)`, substitute `foo.x` for `x`, `foo` for `y`, and `{a:1}` for `z`. In step 1, `foo.x` is evaluated; the result is the `x` property of the `{}` object. In step 2.3, `foo` gets set to `{a:1}`. In step 3, the result of step 2 (the `{a:1}` object) gets assigned to the result of step 1 (the `x` property of the `{}` object). So the final value of `foo` is `{a:1}`, and the final value of `bar` is `{x:{a:1}}`. – Michael Liu Dec 02 '15 at 14:57
  • Ok, but why doesn't the `x` property of the `{}` object get assigned with the `{a:1}` object....shouldn't the `x` property be created? or to put it a little differently....why is `bar` necessary? – Danield Dec 02 '15 at 15:41
  • The `x` property of the `{}` object *does* get assigned with the `{a:1}` object. The `bar` variable isn't necessary; I just added it for debugging and explanatory purposes. Without `bar`, there wouldn't be a way to refer to the `{}` object after `foo` gets set to the `{a:1}` object. By adding `bar`, you can execute `console.log(foo)` and `console.log(bar)` to see the final states of the `{a:1}` and `{}` objects. – Michael Liu Dec 02 '15 at 16:21
  • @MichaelLiu is foo.x = foo = {a: 1}; break down to foo.x = {a: 1}; foo = {a: 1}; ?? – Praveen Jul 13 '16 at 14:39
  • 1
    @link2pk: Not quite, because the former creates a single `{a: 1}` object but the latter creates two independent `{a: 1}` objects. It would be more accurate to write the latter like this: `var temp = {a: 1}; foo.x = temp; foo = temp;` – Michael Liu Jul 13 '16 at 15:03
  • ok @MichaelLiu . And, what would be more accurate to write former? or is it something which can't be broken into two or more statements? – Praveen Jul 13 '16 at 16:00
  • @link2pk: I'm not sure what you're asking. `foo.x = foo = {a: 1};` is basically equivalent to `var temp = {a: 1}; foo.x = temp; foo = temp;`. – Michael Liu Jul 13 '16 at 20:00
1

Edited the answer to make it simple

First of all you have to understand the differnce between Reference- and Value- Type.

var foo = {};

foo variable holds a Reference to an object in memory, lets say A

Now, there are two arts of accessors: Variable Accessor and Property Accessor.

So foo.x = foo = {a:1} can be understood as

[foo_VARIABLE_ACCESSOR][x_PROPERTY_ACCESSOR] = [foo_VARIABLE_ACCESSOR] = {a:1}

!!! Accessor chain is evaluated first to get the last accessor, which is then evaluated associative.

A['x'] = foo = {a:1}

Property Accessor are seperated into setters and getters

var foo = { bar: {} };
foo.bar.x = foo = {a:1}

Here where have decared two nested objects foo and bar. In memory we have then two object A and B.

[foo_VAR_ACCESSOR][bar_PROP_GETTER][x_PROP_ACCESSOR] = [foo_VAR_ACCESSOR] = {a:1}

> A[bar_PROP_GETTER][x_PROP_ACCESSOR] = [foo_VAR_ACCESSOR] = {a:1}
> B[x_PROP_ACCESSOR] = [foo_VAR_ACCESSOR] = {a:1}
> B['x'] = foo = {a: 1}

Here you have little example

var A = {};
var B = {}
Object.defineProperty(A, 'bar', {
    get () {
        console.log('A.bar::getter')
        return B;
    }
})
Object.defineProperty(B, 'x', {
    set () {
        console.log('B.x::getter')
    }
});

var foo = A;
foo.bar.x = foo = (console.log('test'), 'hello');

// > A.bar.getter
// > test
// > B.x.setter
tenbits
  • 7,568
  • 5
  • 34
  • 53
0

Great question. The thing to remember here is that JavaScript uses pointers for everything. It's easy to forget this since it is impossible to access the values representing memory addresses in JavaScript (see this SO question). But realizing this is very important in order to understand many things in JavaScript.

So the statement

var foo = {};

creates an object in memory and assigns a pointer to that object to foo. Now when this statement runs:

foo.x = foo = {a: 1};

the property x is actually getting added to the original object in memory, while foo is getting assigned a pointer to a new object, {a: 1}. For example,

var foo, bar = foo = {};
foo.x = foo = {a: 1};

shows that if foo and bar are pointing to the same object initially, bar (which will still point to that original object) will look like {x: {a: 1}}, while foo is simply {a: 1}.

So why doesn't foo look like {a: 1, x: foo}?

While you are right in that assignments are right associative, you must also realize that the interpreter still reads from left to right. Let's take an in-depth example (with some bits abstracted out):

var foo = {};

Okay, create an object in memory location 47328 (or whatever), assign foo to a pointer that points to 47328.

foo.x = ....

Okay, grab the object that foo currently points to at memory location 47328, add a property x to it, and get ready to assign x to the memory location of whatever's coming next.

foo = ....

Okay, grab the pointer foo and get ready to assign it to the memory location of whatever's coming next.

{a: 1};

Okay, create a new object in memory at location 47452. Now go back up the chain: Assign foo to point to memory location 47452. Assign property x of the object at memory location 47328 to also point to what foo now points to--memory location 47452.

In short, there is no shorthand way to do

var foo = {a: 1};
foo.x = foo;
Community
  • 1
  • 1
bowheart
  • 4,616
  • 2
  • 27
  • 27