If we need to copy an object thats shallow then we have two options. I’ll show the one that has the most browser compatibility first, and then the new one for ECMAScript 2020.
The spread operator allows us to iterate over any iterable (array, map, set, string) and as of 2018 we can iterate over objects although their not technically an iterable like map. We use the spread operator by three dots before the iterable like so …anIterable. Here’s an example of all except object which we will cover in a bit.
The Object.Assign() is a new addition we got in 2019 that does the same object copying
Now the two before mentioned options will be perfect for most situations. However, there will be times when an object property references another property, or a nested object. When you make a shallow copy it just makes a copy of the data, but it keeps a pointer to any circular references or nested objects. However, by using JSON.parse(JSON.stringify(object)) we can get around this
Now if this works as expected our tired Employee should not have changed all the objects except the animalTypeJSON object
Perfect our tired employee wasn’t able to change the hawk animal class to mammal