Copying Arrays and Objects in Javascript

It’s important to note that in Javascript, when you set new variable to an existing array or object, the new variable will be a reference to the original array or object. So, if there are any changes to the original array or object, these will be reflected in the new variable.

var foo = [1, 2, 3];
var bar = foo;
bar[1] = 5;
alert(foo[1]);
// alerts 5

For arrays, there’s an easy method to make a copy: use the slice method.

var foo = [1, 2, 3];
var bar = foo.slice(0);
bar[1] = 5;
alert(foo[1]);
// alerts 2

Coincidentally, you could set foo = [] after assigning bar = foo, which would effectively create a new array and decouple foo from bar (in this case, foo is now looking at a new memory address while bar is looking at the old memory address of foo).

Copying an object is a little bit more involved. Javascript libraries such as jQuery and Backbone/Underscore have functions that can copy objects. Here’s a pure Javascript method:

Object.prototype.clone = function() {
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {
      newObj[i] = this[i].clone();
    } else newObj[i] = this[i]
  } return newObj;
};

var foo = {a: 1, b: 2, c: 3};
var bar = foo;
bar.b = 5;
alert(foo.b);
// alerts 5

var foo = {a: 1, b: 2, c: 3};
var bar = foo.clone();
bar.b = 5;
alert(foo.b);
// alerts 2

See Grey Wyvern’s Blog