Using slice() to copy an array

Fernando Daciuk
Daily JS Tips
Published in
1 min readJan 7, 2016

In JavaScript, objects are passed by reference. When you create an object, it takes up a space in memory. Array is a kind of object.

var arr = [];
var arr2 = [];
console.log(arr === arr2); // false

The above code means that, although the content looks the same, actually two new objects were created in two different places on memory.

But, if you assign an object to another variable, they’ll point to the same object:

var arr = [];
var arr2 = arr;
console.log(arr === arr2); // true

It means that, if you change any of these objects, the other also will be changed:

arr[0] = 'first item';
console.log(arr2[0]); // 'first item'

And, if you want to manipulate the objects separately, you can’t.

How to solve?

We can use the slice() method of Array:

var arr = [1, 2, 3];
var arr2 = arr.slice();
console.log(arr === arr2); // false

Now, we have a copy of the first array, but in two different objects :)

That’s all folks! See ya!

--

--