Javascript can be a little bit of a quirky language sometimes. One of those times is when assigning objects to variables.

You see, normal data types in Javascript usually get assigned to a variable by value, which is the standard way of working with variables and everyone is happy.

The problem creeps in when assigning objects. Objects get assigned to objects by reference in Javascript, which means that ONLY the reference to the object gets assigned to the new variable, and now both variables will reference the same object.

The side-effect of this is that if you change the object, then all references to it will show the change too.

This is not always what we want though. Sometimes we want a new object to be created when we assign the object – ie, assign the object by value rather than by reference.

Now, Javascript does not support this functionality by default, but it is possible to write a function to clone an object, and then return the new object that can be assigned to a variable.

Here is some code to do this that I found on a blog post by Keith Devens.

function clone(obj){

    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = new obj.constructor(); // changed (twice)

    for(var key in obj)
        temp[key] = clone(obj[key]);

    return temp;