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
JavaScript Function() Constructor
The JavaScript Function() constructor is used to create new function objects dynamically. By using the Function() constructor with the new operator, developers can define functions on the fly, passing the function body as a string. This allows for greater flexibility in situations where functions ne
2 min read
Default Constructor in JavaScript
In JavaScript, a default constructor is not explicitly defined like in some other programming languages such as Java or C++. In JavaScript, objects can be created without a formal constructor. When you create an object using the new keyword along with a constructor function, that function serves as
2 min read
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 Generator() Constructor
In JavaScript, there is no particular Generator() constructor but instead, we can use generator function declaration to construct a Generator object which is iterable as the Generator object is a subclass of the Iterable class. Generators are usually used to create functions that can be exited and r
1 min read
JavaScript Proxy() Constructor
JavaScript proxy() constructor is used to return the proxy constructor function for the object(e.g. property lookup, assignment, enumeration, function invocation, etc). Syntax: let p = new Proxy(target, handler); Parameter: The proxy object accept two parameters as mentioned above and described belo
2 min read
JavaScript Number() Constructor
Javascript Number() Constructor is used to create a new number object but, if we call it as a function on another data type it will perform type conversion to number if possible. Syntax: Number(object) Parameters: This function accepts a single parameter as mentioned above and described below: objec
2 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
Describe closure concept in JavaScript
In this article, you will learn about the concept of closure in Javascript & how to apply it on various functions. The closure in javascript is a way to combine all the functions & binds them in bundles with the lexical environment. We will deep dive into the closure concept as we grow in th
9 min read
JavaScript Generator constructor Property
JavaScript Generator constructor property is used to return the Generator constructor function for the object. The function which is returned by this property is just the reference to this function, not a Generator containing the functionâs name. The JavaScript number constructor, string constructor
1 min read