로고로고

[Week4] JS의 얕은 복사와 깊은 복사

2024년 11월 9일

얕은 복사(Shallow Copy)깊은 복사(Deep Copy)객체나 배열을 복사할 때 원본과의 참조 관계가 어떻게 유지되는가에 따라 나뉘는 개념

 

1. 얕은 복사 (Shallow Copy)

 

예시 코드

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
성능빠름느릴 수 있음
사용 상황간단한 평면 객체 복사중첩 구조, 상태 관리 등에서 필요