Why is foo.x === undefined?

There is code:

let foo = {};

foo.x = foo = {n: 2};

console.log(foo.x === undefined);


Why is foo.x === undefined? If possible, simple language, and where you can read about it?
March 12th 20 at 08:40
1 answer
March 12th 20 at 08:42
Solution
Quite simply, though not quite obvious.
Expression:
foo.x = foo = {n: 2};
is equivalent to:
foo.x = (foo = {n: 2});

We assign the object ID of the foo property x, which is equal to the result of the operation assignment ID of the foo object reference { n: 2 }.

To verify this it is sufficient to add the variable bar is assigned the initial value of foo, and output at the end:
let foo = {};

const bar = foo;

foo.x = (foo = {n: 2});

console.log(foo.x === undefined); // true

console.log(bar); // { x: { n: 2 } }

console.log(bar.x === foo); // true


Key differences between the assignment operations that are important to understand:
foo.x = - assignment properties of a particular object. At the time of the call in our example this is {}.
foo = - assign a value to the identifier foo. This can be a primitive, object reference, or function. In our case, this object { n: 2 }.

Find more questions by tags JavaScript