[Week4] JS의 얕은 복사와 깊은 복사
2024년 11월 9일
얕은 복사(Shallow Copy)와 깊은 복사(Deep Copy)는 객체나 배열을 복사할 때 원본과의 참조 관계가 어떻게 유지되는가에 따라 나뉘는 개념
1. 얕은 복사 (Shallow Copy)
- 1단계(1-depth)의 값만 복사
- 중첩된 객체나 배열은 원본의 참조를 공유
- 복사된 객체에서 중첩된 속성을 수정하면 원본도 함께 변경
예시 코드
const original = {
name: "Lee",
address: { city: "Seoul" }
};
const shallow = { ...original };
shallow.name = "Kim";
shallow.address.city = "Busan";
console.log(original.name); // "Lee" ← 기본값은 안 바뀜
console.log(original.address.city); // "Busan" ← 바뀜
2. 깊은 복사 (Deep Copy)
- 중첩된 객체나 배열까지 모두 새로운 객체로 복사
- 복사된 객체는 원본과 완전히 독립적인 메모리
예시 코드
const original = {
name: "Lee",
address: { city: "Seoul" }
};
const deep = JSON.parse(JSON.stringify(original));
deep.address.city = "Busan";
console.log(original.address.city); // "Seoul" ← 안 바뀜
항목 | 얕은 복사 (Shallow Copy) | 깊은 복사 (Deep Copy) |
복사 대상 | 1단계(1-depth) 값만 복사 | 중첩 객체/배열까지 모두 복사 |
원본 영향 여부 | 중첩된 속성은 영향을 줌 | 완전히 독립적인 객체 |
사용 예시 | Object.assign, 전개 연산자 | structuredClone, lodash.cloneDeep, JSON |
성능 | 빠름 | 느릴 수 있음 |
사용 상황 | 간단한 평면 객체 복사 | 중첩 구조, 상태 관리 등에서 필요 |