Skip to content

JavaScript clone object | 3 Ways with Examples

  • by

JavaScript clone objects can do Native deep cloning and shallow copy. A deep copy means that all of the values of the new variable are copied and disconnected from the original variable. A shallow copy means that certain (sub-)values are still connected to the original variable.

Using Spread syntax or Object.assign() or JSON parse you can do it.

Summarize the differences between the ways to clone an object in JavaScript:

Clone MethodShallow/DeepClones nested objects/arraysCopies object referencesCopies object properties with object type
Object.assign()ShallowNoYesNo
Spread operatorShallowNoYesNo
JSON.stringify() + JSON.parse()DeepYesNoYes

Example JavaScript clone object

A simple example code clone an object using different techniques.

Using Spread syntax

Using spread will clone your object. Note this will be a shallow copy. However, the deeper objects are referenced.

<!DOCTYPE html>
<html>
<body>

  <script>
    const person = {
      name: 'John',
      age: 25,
    }

    // cloning the object
    const clonePerson = { ... person}

    console.log(clonePerson);

    // changing the value of clonePerson
    clonePerson.name = 'Peter';

    console.log(clonePerson);
    person.name = 'New';
    
    console.log(person);
  </script>

</body>
</html> 

Output:

JavaScript clone object

Using Object.assign()

It will also create a shallow copy of the object.

const person = {
    name: 'John',
    age: 25,
}

// cloning the object
const clonePerson = Object.assign({}, person);

console.log(clonePerson);

// changing the value of clonePerson
clonePerson.name = 'Peter';

console.log(clonePerson.name);
console.log(person.name);

Output:

{name: "John", age: 25}
Peter
John

Using JSON.parse()

This way will give you a deep copy.

const person = {
    name: 'John',
    age: 25,
}

// cloning the object
const clonePerson = JSON.parse(JSON.stringify(person));

console.log(clonePerson);

// changing the value of clonePerson
clonePerson.name = 'Peter';

console.log(clonePerson.name);
console.log(person.name);

Comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading