1
var obj1 = {};
var obj2 = {};
var copyObj1 = obj1; 
var copyObj2 = obj2;

copyObj1 = {
    name :'abc'
};

copyObj2.name = 'xyz';

console.log("obj1",obj1); // obj1 {}
console.log("obj2",obj2); // obj2 { name: 'xyz' }
console.log("copyObj1",copyObj1); // copyObj1 { name: 'abc' }
console.log("copyObj2",copyObj2); // copyObj2 { name: 'xyz' }
  1. Why is obj1 value not the same as copyObj1, although copyObj1 is a reference of obj1?
  2. What is the difference if we assign value by {name:'abc'} and obj1.name ='abc'?
lorond
  • 3,856
  • 2
  • 37
  • 52
  • `copyObj1 = {...}` is a reassignment that is, `copyObj1` holds a reference to another object afterwards. `copyObj2.name = 'xyz'` is a mutation that is, `copyObj2` holds the same object, but changes its properties. Look into [pass by value/by sharing evaluation strategies](http://stackoverflow.com/a/38533677/6445533) for more information. –  Aug 03 '16 at 12:10

4 Answers4

2

1) Why is obj1 value not the same as copyObj1, although copyObj1 is a reference of obj1?

Answer: -

You are storing the reference of obj1 to copyObj1.But this statement

copyObj1 = {
   name: 'abc'
};

creates a new object of copy1 and the reference to obj1 is now lost.

2) What is the difference if we assign value by {name:'abc'} and obj1.name ='abc'?

Answer:-

The difference between the two is when you do

a = {name: 'abc'} or a = {};

you are creating a new object and any previous reference of the object is now lost and doing

a.name = 'abc';

just changes the property value of the object.

ninjawarrior
  • 328
  • 1
  • 7
1
copyObj1 = {
  name :'abc'
};

sets copyObj1 to a whole different object, so it now no longer points to the object pointed to by obj1

When you did

   copyObj2.name = 'xyz';

You assigned a new property name to copyObj

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0
   copyObj1 = {
       name :'abc'
   };

creates a new object, with an address that differs from obj1

 copyObj2.name = 'xyz'

doesn't, it just changes the existing copyObj2 which is in fact the same object as obj2, just by a different referencing name.

Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45
0

obj1 is not a reference to copyObj1 because you reassigned copyObj1 to a new Object with

copyObj1 = { name : 'abc' };

So they point to different Objects.

With {name: "xyz"} you create a new Object with the property "name" while obj1.name adds a new property to an existing Object.

Philipp Brucker
  • 299
  • 1
  • 4
  • 11