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 Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read