Easy Deep Copy of Array Javascript I recently learned about the difference between a copy and a deep copy. Some people where writing some rather lengthy functions to in order to create a deep copy. 

Then I was just playing around and wondering if there is anything wrong with the following method:

var newDeepCopy = originalArray.concat();


Right, so... just concat the original array with... nothing? Am I missing anything?
What you're doing there is copying the array, not its contents. I.e. it's a shallow copy.

As mherzig mentions in a comment, what you end up with is an extra array containing references to the same elements as the first one. As long as those elements are primitive/immutable values, you're fine. But not so with other objects.

Besides, the conventional way of copying an array is to use slice() or slice(0) - not concat() (although the result is the same).

Anyway, as an example:

var obj = { foo: "bar" };
var array1 = [1, 2, obj];

// shallow copy
var array2 = array1.concat();

// changing a primitive works as you might expect
array2[0] += 10;
console.log(array1); // =&gt; [1, 2, { foo: "bar" }]
console.log(array2); // =&gt; [11, 2, { foo: "bar" }]

// but the object hasn't been copied, merely referenced in two places,
// so changing it via one array means it's changed in the other as well
array2[2].foo = "Hello, world!";
console.log(array1); // =&gt; [1, 2, { foo: "Hello, world!" }]
console.log(array2); // =&gt; [11, 2, { foo: "Hello, world!" }]


Hence why people go to great lengths to make deep copies, where the entire contents is copied, so there are no shared references to the same things.

Basically, you want shallow copies if you're just going to be manipulating the array itself (e.g. calling push, pop, splice, sort etc.), and don't want side-effects. E.g. a function that takes an array as its argument is usually best served making a shallow copy, if it intends to mess around with that array.

You want deep copies if you truly want to copy everything, because you're going to be changing the contents, or because you want to avoid other code altering something you hold a reference to.