Skip to main content

Copying Objects in JavaScript

·2 mins

The other day I got tripped up by the way JavaScript assigns variables. In many languages, assigning a variable to another variable creates a copy of the existing variable. If you wanted to make the new variable a reference to the existing variable, you would have to explicitly define that. For example, in Perl you can do the following:

#!perl

my @array = (1, 2, 3);
my @newArray = @array; # creates a copy of the @array
my $arrayRef = @array; # creates a reference to @array

In JavaScript things are a bit different. While assigning a boolean or string to a variable does make a copy of that value, assigning an array or an object to a variable actually makes a reference to the value. If your not careful this can easily catch you out, as you might expect to be able to change the new variable without affecting the old object.

Strangely, nothing exists in JavaScript that will help you clone an object. However, other people have came across this and kindly shared their solutions. The code I am now using was submitted by Jozef Sakalos over at the ExtJS forums and is displayed below in a more neutral namespace.

var cloneObject = function(o) {
    if(!o || 'object' !== typeof o) {
        return o;
    }
    var c = '[object Array]' === Object.prototype.toString.call(o) ? [] : {};
    var p, v;
    for(p in o) {
        if(o.hasOwnProperty(p)) {
            v = o[p];
            if(v && 'object' === typeof v) {
                c[p] = cloneObject(v);
            }
            else {
                c[p] = v;
            }
        }
    }
    return c;
};

So to copy an object you can now do the following:

var array = (1, 2, 3);
var arrayRef = array; // reference of the array
var newArray = cloneObject(array); // copy of the array