Open In App

What is Shallow Copy in JavaScript ?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a shallow copy refers to creating a new object or array and copying the top-level structure of the original data structure. However, for nested objects or arrays within the original structure, only references to those nested objects or arrays are copied, rather than duplicating them. This means that changes made to nested objects or arrays within the original structure will also affect the copied structure, and vice versa.

Example: Here, slice() creates a shallow copy of the original array. While the top-level elements are duplicated, the nested array and object within the array are still shared between the original and copied arrays. Therefore, modifications to the nested elements in the original array reflect in the copied array as well.

Javascript




const originalArray =
    [1, [2, 3], { key: 'value' }];
 
// Shallow copy using slice()
const shallowCopyArray = originalArray.slice();
 
// Modifying the originalArray
originalArray[0] = 10;
originalArray[1][0] = 20;
originalArray[2].key = 'updated';
 
console.log(originalArray);
// [10, [20, 3], { key: 'updated' }]
 
console.log(shallowCopyArray);
// [1, [20, 3], { key: 'updated' }]


Output

[ 10, [ 20, 3 ], { key: 'updated' } ]
[ 1, [ 20, 3 ], { key: 'updated' } ]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads