3

Can anyone tell how the output became undefined?

var foo = {n: 2};
foo.x = foo = {n: 2};
console.log(foo.x); // undefined
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75

3 Answers3

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

The foo.x refers to the property x of the object referred to by foo. However, foo = { n: 2 } assigns a completely new object to foo. x is indeed assigned to an object, but that object is immediately replaced by another object. The object with the x property isn’t referenced by anything anymore.

You can read that line as

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

Graphical explanation

var foo = { n: 2 };

First object is assigned to foo

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

foo is reassigned to a second object, but foo.x still points to the first object.

console.log(foo.x);

Trying to access foo.x actually accesses the x property of the second object.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
2

I'll break down the assignment and output of each variable as it plays out.

var foo = {n:2}
// foo: Object {n: 2}
// foo.x: undefined

foo.x = 3
// foo: Object {n: 2, x: 3 }
// foo.x: 3

foo.x = foo
// foo: Object {n: 2, x: Object {n:2, x: Object (recursive) } }
// foo.x: Object {n: 2, x: Object {n:2, x: Object (recursive) } }

foo.x = foo = {n: 2}
// foo: Object {n: 2}
// foo.x: undefined

The last line, as you can see, resets foo to equal {n: 2} which makes foo.x non-existent (because you have overwritten the foo object)

Shivam
  • 1,345
  • 7
  • 28
Wes Foster
  • 8,770
  • 5
  • 42
  • 62
0

Your code is exactly the same as this one,

var foo = {n:2}; // foo ==> {n:2}
foo.x = {n:2}; // foo ==> {n:2,x:{n:2}}
foo = {n:2}; // foo ==> {n:2}
console.log(foo.x); // undefined 

because there's no "x" key in your object

Shivam
  • 1,345
  • 7
  • 28
Ayyoub
  • 1,315
  • 1
  • 16
  • 37