Copying Array or Object can be tremendously confusing if we don’t know that they are different from primitive typed values like string, boolean, or number.

Let’s start with them. I can guarantee that we can copy primitive typed values this way.

If we change the value of year to something else, then nothing happens to thisYear. As expected.

The same thing goes to boolean and string values.

Let’s say we have an array.

We try to make a copy of array the same way we copy number, boolean, and string.

You might think we can just do something like this, expecting that players will not be affected.

However what happens when we update that array?

Now here is the problem! We have edited the original array too! Why? It’s because that is an array reference, not an array copy. They both point to the same array! So, how do we fix this?

• By using old fashioned [].slice.
• By using [].concat.
• By using the new ES6 spread.

Object and Array act the same way when it comes to copying its own properties. Let’s say we have a person object.

This kind of statement is completely wrong.

How do we fix that?

• Using Object.assign instead.
• We will hopefully soon see {...spread}. It’s next generation of EcmaScript. Every cool kid will be using this frantically. It’s the future!

Things to note that this is only 1 level deep, both for Array and Object. Lodash has a cloneDeep method, but you should think twice before using it.

Well, I borrow too many words from Wes Bos. I owe him a beer. That’s it for today.