Shallow Copy in JavaScript

A shallow copy of an object refers to a bitwise copy. It involves creating a new object with identical values to the original object.

Understanding Shallow copy requires a grasp of different data types. This segment will provide a concise overview of data types before delving into the concept of Shallow copy in JavaScript. Additionally, we will explore a demonstration illustrating the functionality of shallow copy.

Data Types in JavaScript

In essence, Data types can be categorized into two main groups as outlined below:

  1. Fundamental Data types: These consist of Boolean, byte, char, short, long, double, and int.
  2. Composite Data Types: These encompass arrays and objects.

We will understand its role in the shallow copy.

What is Shallow Copy

When making a shallow copy of an object, it duplicates the reference to the original object's address. If any object field points to other objects, the shallow copy merely duplicates the reference address (i.e., the memory location) of the object without generating a new object. This sets apart a shallow copy from a deep copy. The shallow copy duplicates the primary properties of the object while the inner object remains common between the original and the duplicate. Essentially, a shallow copy reproduces the structure of the collection without replicating the values, resulting in both collections sharing the elements of the initial collection.

Typically, a shallow copy is considered straightforward and convenient as it involves duplicating the reference address without creating a new object. This principle is applicable not just to arrays but also to other data structures.

When dealing with primitive data types, duplicating a variable results in the value being copied to a different memory location that the new variable references. This process ensures that each copy is a distinct entity with its own memory allocation. For instance, if we assign the value of variable 'a' to variable 'c' by executing c = a, a separate copy of 'a' is made. Consequently, modifying the value of c will not impact the original value stored in variable a. This behavior stems from the immutable nature of values once they are initialized.

When dealing with reference data types, they store the memory address of the object, which indicates the location where the object is stored. Consequently, value copying functions effectively with reference data types. Hence, both shallow and deep copies belong to the category of reference data types.

Next, let's explore the concept of a Shallow copy through an illustrative example.

Example of Shallow Copy

Imagine having two objects, obj1 and obj2, with obj2 referencing obj1. Consequently, obj2 will share the identical memory address as obj1, resulting in both objects having the same memory location and pointing to that same address exclusively.

The diagram provided below illustrates the example effectively:

Example Code Implementation

Listed below is a code snippet demonstrating the creation of a shallow copy for the student's information:

Example

<script>

let student = {

    name: 'Michael',

    department: 'Computer Science',

            enroll_no: '1829939',

    permanent_address: {

        house_no: '200',

        locality: 'Simi Valley',

        city: 'New York',

        country: 'USA'

    }

};

console.log("Before applying Shallow Copy");

console.log(student);

let createcopy = Object.assign({}, student);

createcopy.name = 'Abraham Smith';

createcopy.enroll_no = '1829887';

createcopy.permanent_address.house_no = '321';

createcopy.permanent_address.locality = 'Santa Maria';

createcopy.permanent_address.city = 'California';

console.log("After applying Shallow Copy");

console.log(createcopy);

</script>

Output:

The output of the above code is shown below:

Code Explanation:

  • In the above code, we have created an object 'student' for which we have initialized some detailed entities.
  • Then, before applying the shallow copy, we got the values on the console that has been initialized.
  • Next, we have initialized another object, 'createcopy', for creating the shallow copy of the 'student' object'. Then assigned the 'student' object to 'createcopy' using Object.assign. It means both 'student' (obj1) and 'createcopy' (obj2) objects will point to the same memory address, as you can understand from the above shown image.
  • Then, we have set different values for the 'createcopy' object from the 'student' object entities i.e., name, enrollno, permanentaddress.
  • Finally, we have console log the obj2, i.e., 'createcopy' object, and then we can see in the output that after modifying, we got the different assignment of the values for the same entities.
  • Also, we should notice that only those entities values got changed, which we have assigned again for the 'createcopy' object. Rest entities values are the same i.e., 'department' and 'country'.

Therefore, by using this method, a shallow copy of an object can be generated and utilized to assign various values to the properties of the object.

Input Required

This code uses input(). Please provide values below: