What is an Object?
JavaScript employs objects to encapsulate data or functionalities that are interconnected in some manner. An object is essentially a set of properties, which may consist of both methods and basic data values. In essence, objects are constructs that possess both state and behavior. For example, items such as cars, pens, bicycles, chairs, glasses, keyboards, monitors, among others, can all be regarded as objects within the JavaScript framework.
Indeed, in JavaScript, every entity is regarded as an object because it is fundamentally an object-oriented language.
How to Copy an Object in JavaScript?
In JavaScript, replicating an object is straightforward when it comes to primitive data types. However, to duplicate objects without maintaining references, we employ different methods like deep cloning and shallow cloning.
Deep Copying object
JavaScript includes a functionality known as "deep copy," which enables the creation of an exact replica of any encountered object. When utilizing deep copy, the resulting object will not have any shared references with the source object, resulting in a thorough duplication. Consequently, alterations made to the duplicated object will have no impact on the original object.
Shallow copying object
In JavaScript, the process of copying an object occurs at the bitwise level. This indicates that only the topmost level of the object will be duplicated.
How to Copy an Object without reference in JavaScript?
In JavaScript, when the goal is to duplicate an object without maintaining a reference, we can utilize various techniques, including "Object.assign" and "JSON.parse". When an object is replicated through the assignment operator in JavaScript, both the object and its associated value are kept in a variable on the right-hand side.
Using the object.assign method to copy objects
In JavaScript, the object.assign function serves the purpose of duplicating objects without creating references. Utilizing this method allows us to transfer the values and attributes from a specified source object to a designated target object.
Syntax
Let’s examine the syntax required to utilize the object.assign method:
Object.assign(target, source)
Example
// Define an object called `originalObj`.
const originalObj = {
name: "Rohit",
age: 20,
city: "Noida"
};
// Use the `Object.assign` method to create a copy of `originalObj` called `copiedObj`.
const copiedObj = Object.assign({}, originalObj);
// Modify the `name` property of `copiedObj`.
copiedObj.name = "Nikhar";
// Print both objects' `name` property to the console.
console.log(`originalObj.name: ${originalObj.name}`); // Output: originalObj.name: Rohit
console.log(`copiedObj.name: ${copiedObj.name}`); // Output: copiedObj.name: Nikhar
Output:
Using JSON.parse method to Copy objects
In JavaScript, the functions JSON.parse and JSON.stringify can be utilized to carry out deep copying. This technique enables us to duplicate an object without creating a reference to the original.
Syntax
Let's see the syntax of JSON.prase method:
JSON.parse(JSON. stringify(object)
Example
// Define an object called `originalObj`.
const originalObj = {
name: "John",
age: 30,
city: "New York"
};
// Use the `JSON.stringify` method to convert `originalObj` to a string.
const originalObjString = JSON.stringify(originalObj);
// Use the `JSON.parse` method to convert the string back to an object called `copiedObj`.
const copiedObj = JSON.parse(originalObjString);
// Modify the `name` property of `copiedObj`.
copiedObj.name = "Jane";
// Print both objects' `name` property to the console.
console.log(`originalObj.name: ${originalObj.name}`); // Output: originalObj.name: John
console.log(`copiedObj.name: ${copiedObj.name}`); // Output: copiedObj.name: Jane
Output:
Benefits of Using Copy Object without Reference
Duplicating objects without retaining the reference can offer a variety of advantages, including:
Preventing Unintended Modifications
In JavaScript, when we create a copy of an object by not using the reference, we effectively create distinct instances. This implies that any changes applied to the duplicated object will not influence the original object, which can aid in avoiding unintended mistakes.
Maintaining Data Integrity
In JavaScript, generating separate copies of objects allows us to guarantee that each instance maintains its own distinct set of data. This practice is particularly beneficial when handling intricate data structures or when transferring data across various components of our codebase.
Isolating Changes
We can modify objects for particular scenarios without altering the original instance, and by generating a copy of an object without reference, we can separate those modifications. This practice enhances the modularity of our code and simplifies maintenance.
Avoiding Shared State Issues
In JavaScript, objects are inherently passed by reference. To put it simply, when an object is passed into a function or assigned to a different variable, both references will lead to the identical object stored in memory. To prevent complications arising from unintended modifications to an object’s state, we can create copies of objects that do not share references.
Cloning Nested Objects
When handling nested objects or arrays, performing a copy that does not retain a reference guarantees that every layer of the data structure is replicated. This approach helps avoid unforeseen issues that may arise when only the top-level object is duplicated.
In general, duplicating objects without creating references in JavaScript enhances the stability of the code, safeguards data integrity, and aids in avoiding bugs that may arise from unintentional side effects caused by object mutations.