Question: What is the most efficient way to clone a JavaScript object? I've seen `obj = eval(uneval(o));` being used, but [that's non-standard and only supported by Firefox](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval).  

 I've done things like `obj = JSON.parse(JSON.stringify(o));` but question the efficiency.   

 I've also seen recursive copying functions with various flaws.

I'm surprised no canonical solution exists.

Answer: 
Code:

```
// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned
function extend(from, to)
{
    if (from == null || typeof from != "object") return from;
    if (from.constructor != Object && from.constructor != Array) return from;
    if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
        from.constructor == String || from.constructor == Number || from.constructor == Boolean)
        return new from.constructor(from);

    to = to || new from.constructor();

    for (var name in from)
    {
        to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name];
    }

    return to;
}

```

Test:

```
var obj =
{
    date: new Date(),
    func: function(q) { return 1 + q; },
    num: 123,
    text: "asdasd",
    array: [1, "asd"],
    regex: new RegExp(/aaa/i),
    subobj:
    {
        num: 234,
        text: "asdsaD"
    }
}

var clone = extend(obj);

```
**Cloning an object using today's JavaScript: [ECMAScript 2015](https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015)** (formerly known as ECMAScript 6)

```
var original = {a: 1};

// Method 1: New object with original assigned.
var copy1 = Object.assign({}, original);

// Method 2: New object with spread operator assignment.
var copy2 = {...original};

```

Old browsers may not support ECMAScript 2015. A common solution is to use a JavaScript-to-JavaScript compiler like Babel to output an [ECMAScript 5](https://en.wikipedia.org/wiki/ECMAScript#5th_Edition) version of your JavaScript code.

As [pointed out by @jim-hall](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object-in-javascript?page=2&tab=oldest#comment60081951_36177142), **this is only a shallow copy**. Properties of properties are copied as a reference: changing one would change the value in the other object/instance.