객체와 배열의 **구조 분해 할당(Destructuring Assignment)**은 ES6에서 도입된 문법으로, 객체나 배열에서 값을 추출하여 변수에 쉽게 할당할 수 있도록 도와준다.
1. 배열 구조 분해 할당
배열의 구조 분해 할당을 사용하면 배열의 요소를 개별 변수로 쉽게 할당할 수 있어.
🔹 기본 예제
const arr = [1, 2, 3];
const [a, b, c] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
배열의 순서대로 변수를 할당하게 돼.
🔹 필요 없는 값 무시하기
const numbers = [10, 20, 30, 40];
const [first, , third] = numbers;
console.log(first); // 10
console.log(third); // 30
second 값은 생략됐기 때문에 third는 30이 됨.
🔹 기본값 설정하기
const [x, y, z = 100] = [10, 20];
console.log(x); // 10
console.log(y); // 20
console.log(z); // 100 (배열에 값이 없으면 기본값 사용)
🔹 나머지 연산자 (...)
const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest); // [2, 3, 4, 5]
나머지 연산자 ...를 사용하면 나머지 값들을 배열로 저장할 수 있어.
2. 객체 구조 분해 할당
객체의 구조 분해 할당을 사용하면 객체의 속성을 쉽게 변수에 할당할 수 있어.
🔹 기본 예제
const user = { name: "Alice", age: 25 };
const { name, age } = user;
console.log(name); // Alice
console.log(age); // 25
객체의 키(key) 이름과 변수 이름이 동일해야 자동 할당됨.
🔹 변수 이름 변경하기
객체의 키와 다른 이름으로 변수를 만들 수도 있어.
const person = { firstName: "John", lastName: "Doe" };
const { firstName: fName, lastName: lName } = person;
console.log(fName); // John
console.log(lName); // Doe
🔹 기본값 설정하기
const user = { name: "Bob" };
const { name, age = 30 } = user;
console.log(name); // Bob
console.log(age); // 30 (기본값 적용)
객체에 age 값이 없으므로 기본값 30이 적용됨.
🔹 나머지 연산자 (...)
const user = { id: 1, name: "Charlie", age: 40 };
const { name, ...others } = user;
console.log(name); // Charlie
console.log(others); // { id: 1, age: 40 }
객체에서도 ...를 사용하면 나머지 속성을 새로운 객체로 저장 가능.
3. 중첩 구조 분해
객체와 배열이 중첩되어 있을 때도 구조 분해 할당이 가능
🔹 중첩 객체 구조 분해
const company = {
name: "TechCorp",
address: {
city: "Seoul",
zipCode: "12345"
}
};
const { name, address: { city, zipCode } } = company;
console.log(name); // TechCorp
console.log(city); // Seoul
console.log(zipCode); // 12345
address 객체 안의 city, zipCode를 바로 분해하여 사용 가능.
🔹 중첩 배열 구조 분해
const colors = [["red", "green"], ["blue", "yellow"]];
const [[firstColor], [, secondColor]] = colors;
console.log(firstColor); // red
console.log(secondColor); // yellow
배열 안의 배열에서도 구조 분해를 활용할 수 있음.
4. 함수의 매개변수에서 사용
객체 구조 분해 할당은 함수의 매개변수에서도 유용하게 사용돼.
const user = { name: "Emma", age: 22, job: "Developer" };
function introduce({ name, age, job }) {
console.log(`${name}은(는) ${age}살이며, 직업은 ${job}입니다.`);
}
introduce(user); // Emma은(는) 22살이며, 직업은 Developer입니다.
함수의 인자로 객체를 넘길 때, 구조 분해를 하면 가독성이 좋아짐.
✨ 정리 ✨
유형 | 문법 |
배열 구조 분해 | const [a, b] = [1, 2]; |
배열에서 일부 값 무시 | const [a, , c] = [1, 2, 3]; |
배열 기본값 설정 | const [a, b = 10] = [1]; |
나머지 배열 요소 저장 | const [a, ...rest] = [1, 2, 3]; |
객체 구조 분해 | const { name, age } = user; |
객체 속성 이름 변경 | const { name: userName } = user; |
객체 기본값 설정 | const { age = 30 } = user; |
나머지 객체 속성 저장 | const { name, ...rest } = user; |
중첩 구조 분해 | const { address: { city } } = user; |
함수 매개변수에서 사용 | function fn({ name }) {} |
*위 포스팅은 챗GPT 답변을 토대로 작성되었습니다!
'JavaScript' 카테고리의 다른 글
[JS] filter() (0) | 2025.04.24 |
---|---|
[JS] 재귀 기능 (0) | 2025.03.02 |
[JS] 코딩테스트 대비 DFS(깊이 우선 탐색) & BFS(너비 우선 탐색) (0) | 2025.03.02 |
[JS] some()과 reduce()에 대해~ (0) | 2025.02.27 |
[JS] 자바스크립트 split() 메서드 (0) | 2025.02.19 |