JavaScript에서 구조 분해 할당 (초급부터 고급까지)
발행: (2026년 3월 26일 PM 06:36 GMT+9)
3 분 소요
원문: Dev.to
Source: Dev.to
Without Destructuring
const user = {
name: "John",
age: 20,
city: "Mumbai"
};
const name = user.name;
const age = user.age;
const city = user.city;
console.log(name, age, city);
With Destructuring
const user = {
name: "John",
age: 20,
city: "Mumbai"
};
const { name, age, city } = user;
console.log(name, age, city);
Object Destructuring
Basic Assignment
const user = { name: 'Alice', age: 25 };
const { name, age } = user; // name = 'Alice', age = 25
Renaming
const user = { name: 'Alice' };
const { name: userName } = user; // userName = 'Alice'
Default Values
const user = {};
const { city = 'Unknown' } = user; // city = 'Unknown'
Nested Destructuring
const profile = { id: 1, info: { email: 'a@ex.com' } };
const { info: { email } } = profile; // email = 'a@ex.com'
Array Destructuring
Basic Assignment
const colors = ['red', 'blue', 'green'];
const [first, second] = colors; // first = 'red', second = 'blue'
Skipping Values
const colors = ['red', 'blue', 'green'];
const [first, , third] = colors; // first = 'red', third = 'green'
Swapping Variables
let a = 4;
let b = 5;
[a, b] = [b, a]; // a = 5, b = 4
How it works
- 오른쪽 배열
[b, a]가 먼저 평가되어[5, 4]가 생성됩니다. - 왼쪽의 구조분해 할당
[a, b] = [5, 4]가 실행되어a = 5와b = 4가 할당됩니다.
Rest Operator
const numbers = [1, 2, 3, 4];
const [one, ...others] = numbers; // one = 1, others = [2, 3, 4]
Important Points of Destructuring
- 구조분해 할당은 원본 객체나 배열을 수정하지 않으며, 값만 추출합니다.
- 얕은 복사를 생성합니다. 중첩된 객체나 배열은 여전히 원본 데이터를 가리키는 참조입니다.
const user = {
name: "Abhi",
address: {
city: "Jalandhar"
}
};
const { address } = user;
address.city = "Delhi";
console.log(user.address.city); // Delhi (original also changed)
null이나undefined에 대해 구조분해 할당을 시도하면TypeError가 발생합니다.
const { name } = null; // TypeError
Conclusion
JavaScript(ES6에서 도입)에서 구조분해 할당은 객체와 배열에서 값을 추출하기 위한 간결한 문법을 제공하여 가독성을 높이고 반복 코드를 줄여줍니다. 이름 바꾸기, 기본값, 중첩 구조, 나머지 연산자 지원은 물론 임시 변수 없이도 우아하게 변수 교환을 할 수 있습니다.