본문 바로가기
JavaScript

[JavaScript] Shallow Copy vs Deep Copy

by 메이플 🍁 2024. 5. 7.

*해당 포스팅은 챗지피티에 검색결과 내용입니다.

 

In JavaScript, shallow copy and deep copy are techniques used to duplicate objects or arrays.

1. Shallow Copy: A shallow copy creates a new object or array, but doesn't create copies of nested objects or arrays. It means the new object simply references the original object's properties. Modifying a nested object in the shallow copy will affect the original object, as they share the same reference.

let original = { a: 1, b: { c: 2 } };
let shallowCopy = Object.assign({}, original);

console.log(shallowCopy); // { a: 1, b: { c: 2 } }
shallowCopy.a = 3;
shallowCopy.b.c = 4;

console.log(original); // { a: 1, b: { c: 4 } }



2. Deep Copy: A deep copy creates a new object or array and recursively copies all nested objects and arrays as well. This means the new object is completely independent of the original object and modifying it will not affect the original.

let original = { a: 1, b: { c: 2 } };
let deepCopy = JSON.parse(JSON.stringify(original));

console.log(deepCopy); // { a: 1, b: { c: 2 } }
deepCopy.a = 3;
deepCopy.b.c = 4;

console.log(original); // { a: 1, b: { c: 2 } }



It's important to note that using `JSON.parse(JSON.stringify(obj))` for deep copying has limitations. It doesn't work with functions, `undefined`, or symbols, and it can't handle circular references. There are other methods like libraries (e.g., lodash's `_.cloneDeep`) or custom recursive functions that can be used for more complex deep copying needs.

댓글