<h1>Javascript - copying objects with Object.assign()</h1>
<h2>See console output.</h2>
const cout = console.log;

var obj = {
  x: 5, // this is a primitive type
  y: { z: 10 } // this is an object
};
var copyObj = Object.assign({}, obj); // a _shallow_ copy of obj!
// which means only primitive types inside are copied, objects are by reference (pointer)
var copyObj2;
var yObj = { y: {z: 99} };

console.clear();

copyObj.x = 6;
cout("obj.x", obj.x); // will still be 5

copyObj.y.z = 11;
cout("obj.y.z", obj.y.z); // will now be 11

copyObj2 = Object.assign({}, obj, yObj); // another shallow copy of obj, but afterwards yObj overwrites everything
cout("copyObj2", copyObj2);
// will be like obj, but with "y" content from yObj, so "z" will be 99

cout("obj", obj); // x: 5, y: {z: 11}

copyObj2.y.z = 100;
cout("obj.y.z", obj.y.z); // 11, good! So finally copyObj2 is a standalone object without pointers!

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.