Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

Weird behaviour of Object.assign

I recently tried some luck with Spread Syntax in JavaScript, where the results were weird and crazy enough to post this question. My assumptions about Spread Syntax is that it is similar to Object.assign(), but will it vary with the variables of same nature?

a = {a: "a"};
b = {b: "b"};
c = {c: "c"};
d = {d: {e: "e"}};

d = Object.assign(a, b, c, d);
e = { ...a, ...b, ...c, ...d };

console.log("Before Variable Change");
console.log(d);
console.log(e);

a.a = "s";
b.b = "t";
d.d.e = "f";

console.log("After Variable Change");
console.log(d);
console.log(e);
.as-console-wrapper {max-height: 100% !important; height: 100% !important;}

What I have got as a result is:

Before Variable Change
{
  "a": "a",
  "b": "b",
  "c": "c",
  "d": {
    "e": "e"
  }
}
{
  "a": "a",
  "b": "b",
  "c": "c",
  "d": {
    "e": "e"
  }
}
After Variable Change
{
  "a": "s",
  "b": "b",
  "c": "c",
  "d": {
    "e": "f"
  }
}
{
  "a": "a",
  "b": "b",
  "c": "c",
  "d": {
    "e": "f"
  }
}

I could understand that d.e's value will always change because of its "object" nature and they are mutable, so accepted. But when I tried using the ... spread syntax with this, the first value of the object is changed (a.a) but not the second one (b.b). Am I missing something here?


Extra Info:

Checked with Browsers:

Upvotes: 3

Views: 115

Answers (1)

Pointy
Pointy

Reputation: 413682

The Object.assign() function changes the content of the first object parameter, which is a. That's also the return value, so after the first Object.assign() call that sets the value of d, it'll be true that d === a.

Thus the assignment of "s" to a.a will also change d.a because d and a reference the same object.

Just adding my two cents, in a simple way:

In other words, the spread operator does this:

d = Object.assign({}, a, b, c, d);
e = { ...a, ...b, ...c, ...d };

Now both the above are same.

Upvotes: 2

Related Questions