-1

I am trying to do -

var a = {key1: "Value1", key2: "Value2"};
var b = a;
b.key3 = "Value3";

Though I was expecting a to console only {key1: "Value1", key2: "Value2"}

but if I do console.log(a) following is the result -

{key1: "Value1", key2: "Value2", key3: "Value3"}

For the time being I managed to make it work using ES6 Object.assign method like -

var a = {key1: "Value1", key2: "Value2"};
var b = Object.assign({}, a);
b.key3 = "Value3";
console.log(a); // {key1: "Value1", key2: "Value2"}

But I am interested to know about the cause of this in JavaScript.

FYI - I tried to search/google but unable to find as I don't know about the exact phase to follow.

Nesh
  • 2,389
  • 7
  • 33
  • 54

1 Answers1

2

By doing var b = a; it just makes another reference to the same object, which is accessible through both a and b.

The Object.assign() method is used to copy the values of all enumerable own properties from one (or more) object to another object.

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed.
koninos
  • 4,969
  • 5
  • 28
  • 47