0
var o1 = {};
var o2 = { bar: 'hello' };

o1.foo = o2; // in console  {bar: "hello"}
var o3 = o2;// in console  undefined

Why is {bar: "hello"} being printed? Why is undefined being printed?

1 Answers1

0

That doesn't happen - the code creates a new property of o1 named foo, and assigns it the value of o2, which is an object - so the property o1.foo is an object consisting of o2.

var o1 = {};
var o2 = {
  bar: 'hello'
};

o1.foo = o2;

console.log(o1);

The reason you see { bar: "hello" } in the console when you copy/paste the code is because the final return value from the code is { bar: "hello" } (from o1.foo = o2). o1 is still an object containing foo, but the { bar: "hello" } shown in the console is just the return value from the code.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79