Open In App

Copy Constructor in JavaScript

Last Updated : 22 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript does not have a built-in concept of a “copy constructor” like some other programming languages do. However, you can achieve the same result by using techniques for deep and shallow copying.

In JavaScript, when you create an object, it is possible to make copies of that object.

  • Shallow Copy: This method creates a new object, but it only copies the references to the original object’s properties. If the properties are objects themselves, the references to those objects will be shared between the original and the copied object.
  • Deep Copy: This method creates an entirely new and independent copy of the original object and all of its nested objects. Changes made to the properties of the original object or its nested objects do not affect the copied object, and vice versa.

Below are the three different ways to implement a copy constructor in JavaScript, each using a different technique for copying objects:

Using Spread Syntax (Shallow Copy)

Spread syntax in JavaScript allows you to create a shallow copy of an object by expanding its properties. It creates a new object with copies of the original object’s properties, making it suitable for simple objects and avoiding direct reference sharing.

Syntax:

const original = { key: 'value' };
const shallowCopy = { ...original };

Example: Here, the spread syntax is used to create a shallow copy (copiedPerson) of the person object. Changes to the top-level properties like firstName in the copied object do not affect the original. However, changes made to nested objects, such as address, are reflected in both the original and the copied object due to shared references.

Javascript




let person = {
    firstName: 'John',
    lastName: 'Doe',
    address: {
        street: 'North 1st street',
        city: 'San Jose',
        state: 'CA',
        country: 'USA'
    }
};
 
let copiedPerson = { ...person };
 
copiedPerson.firstName = 'Jane';
 
copiedPerson.address.street = 'Amphitheatre Parkway';
copiedPerson.address.city = 'Mountain View';
 
console.log(copiedPerson);


Output

{
  firstName: 'Jane',
  lastName: 'Doe',
  address: {
    street: 'Amphitheatre Parkway',
    city: 'Mountain View',
    state: 'CA',
    country: 'USA'
  }
}

Object.assign() (Shallow Copy)

Object.assign() is a method that copies the values of all enumerable properties from one or more source objects to a target object. It creates a shallow copy, meaning that if the properties are objects, their references will be shared between the original and the copied object.

Syntax:

const original = { key: 'value' };
const shallowCopy = Object.assign({}, original);

Example: Here, Object.assign() is used to create a shallow copy (copiedPerson) of the person object. Changes to the top-level properties like firstName in the copied object do not affect the original. However, changes made to nested objects, such as address, are reflected in both the original and the copied object due to shared references.

Javascript




let person = {
    firstName: 'John',
    lastName: 'Doe',
    address: {
        street: 'North 1st street',
        city: 'San Jose',
        state: 'CA',
        country: 'USA'
    }
};
 
let copiedPerson = Object.assign({}, person);
 
copiedPerson.firstName = 'Jane';
 
copiedPerson.address.street = 'Amphitheatre Parkway';
copiedPerson.address.city = 'Mountain View';
 
console.log(copiedPerson);


Output

{
  firstName: 'Jane',
  lastName: 'Doe',
  address: {
    street: 'Amphitheatre Parkway',
    city: 'Mountain View',
    state: 'CA',
    country: 'USA'
  }
}

JSON.stringify() and JSON.parse() (Deep Copy)

Using JSON.stringify() and JSON.parse() together allows you to create a deep copy of an object. It serializes the original object into a JSON-formatted string and then parses it back into a new object. This results in a completely independent copy with no shared references.

Syntax:

const original = { key: { nestedKey: 'value' } };
const deepCopy = JSON.parse(JSON.stringify(original));

Example: Here, a deep copy of the person object is created using JSON.stringify() to convert the object to a JSON-formatted string and JSON.parse() to parse it back into a new object (copiedPerson). Changes made to properties, both at the top level and within nested objects, do not affect the original object.

Javascript




let person = {
    firstName: 'John',
    lastName: 'Doe',
    address: {
        street: 'North 1st street',
        city: 'San Jose',
        state: 'CA',
        country: 'USA'
    }
};
 
let copiedPerson = JSON.parse(JSON.stringify(person));
 
copiedPerson.firstName = 'Jane';
 
copiedPerson.address.street = 'Amphitheatre Parkway';
copiedPerson.address.city = 'Mountain View';
 
console.log(copiedPerson);


Output

{
  firstName: 'Jane',
  lastName: 'Doe',
  address: {
    street: 'Amphitheatre Parkway',
    city: 'Mountain View',
    state: 'CA',
    country: 'USA'
  }
}



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads