Copy Constructor in JavaScript
Last Updated :
22 Jan, 2024
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:
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()
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'
}
}
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'
}
}
Similar Reads
What is a Constructor in JavaScript? A constructor in JavaScript is a special function that is used to create and initialize objects. When we want to create multiple objects with similar properties and methods, the constructor is used as a blueprint to create similar objects. This is useful when you want to create multiple objects with
8 min read
JavaScript Object Constructors An object is the collection of related data or functionality in the form of key. These functionalities usually consist of several functions and variables. All JavaScript values are objects except primitives. const GFG = { subject : "programming", language : "JavaScript",}Here, subject and language a
4 min read
Multiple Class Constructors in JavaScript Classes were introduced in ES6 and along with it the concepts of Object Oriented Programming were implemented. Even with all these new features, JavaScript does not allow constructor overloading. So, we cannot create multiple constructors for a single class in JavaScript but there are some methods w
3 min read
How to Deep clone in JavaScript? Deep clone in JavaScript refers to creating a complete copy of an object, including all nested objects, ensuring that changes to the cloned object do not affect the original. Unlike shallow cloning, deep cloning requires copying all levels of the objectâs structure.1. Using Spread Operator to Deep C
2 min read
How to clone an array in JavaScript ? In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.Here are some common use cases for cloning an array:Table of ContentUsing the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsing t
6 min read
JavaScript Array copyWithin() Method The Javascript Array.copyWithin() method considers an array first and then copies part of an array to the same array itself and returns it, without modifying its size but yet the modified data whatever user wishes to have in another's place i.e, copies array element of an array within the same array
3 min read