[Sub] ES6 구조 분해 할당(Destructuring) 정리
안녕하세요, 여러분!
오늘은 JavaScript의 ES6 문법 중 하나인 '구조 분해 할당(Destructuring)'에 대해 이야기해보려고 합니다.
이 기능은 코드를 더 간결하고 가독성 높게 작성할 수 있도록 도와줍니다.

1) 구조 분해 할당이란?
구조 분해 할당은 배열이나 객체에서 원하는 값을 추출하여 변수에 할당하는 방법입니다.
이를 통해 변수를 일일이 하나씩 할당하는 번거로움을 줄일 수 있습니다.
2) 배열에서의 구조 분해 할당
배열에서의 구조 분해 할당은 다음과 같이 작성할 수 있습니다.
const colors = ['빨강', '파랑', '노랑'];
const [firstColor, secondColor] = colors; //생략된 변수는 값을 할당하지 않습니다.
console.log(firstColor); // 빨강
console.log(secondColor); // 파랑
3) 객체에서의 구조 분해 할당
객체에서의 구조 분해 할당은 다음과 같이 작성할 수 있습니다:
const person = { name: '홍길동', age: 30 };
const { name, age } = person;
console.log(name); // 홍길동
console.log(age); // 30
4) 기본값 설정
구조 분해 할당 시 기본값을 설정할 수도 있습니다:
const numbers = [1];
const [firstNumber, secondNumber = 2] = numbers;
console.log(firstNumber); // 1
console.log(secondNumber); // 2
5) 함수 매개변수에서의 활용
함수 매개변수에서도 구조 분해 할당을 사용할 수 있습니다.
function printFullName({ firstName, lastName }) {
console.log(`${firstName} ${lastName}`);
}
const person = { firstName: 'John', lastName: 'Doe' };
printFullName(person); // John Doe
6) 중첩된 구조 분해 할당
구조 분해 할당은 중첩된 데이터 구조에서도 사용할 수 있습니다.
객체나 배열 내부에 또 다른 객체나 배열이 있는 경우에 유용하게 활용할 수 있습니다.
const user = {
id: 1,
username: 'johndoe',
details: {
fullName: 'John Doe',
age: 30
}
};
const {
username,
details: { fullName, age }
} = user;
console.log(username); // johndoe
console.log(fullName); // John Doe
console.log(age); // 30
7) 나머지 요소 가져오기
구조 분해 할당을 사용하여 배열에서 나머지 요소를 가져올 수도 있습니다.
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
8) 구조 분해 할당과 함수 반환값
함수에서 여러 값을 반환하는 경우에도 구조 분해 할당을 사용할 수 있습니다:
function getNumbers() {
return [1, 2, 3, 4, 5];
}
const [one, two, ...others] = getNumbers();
console.log(one); // 1
console.log(two); // 2
console.log(others); // [3, 4, 5]
9) 별칭 사용
구조 분해 할당 시 변수명을 다르게 지정하고 싶을 때는 별칭(alias)을 사용할 수 있습니다:
const person = { name: 'Jane', age: 25 };
const { name: fullName, age: years } = person;
console.log(fullName); // Jane
console.log(years); // 25
10) 배열과 객체 동시에 구조 분해 할당
함수 매개변수에서 객체와 배열을 동시에 구조 분해 할당할 수 있습니다:
function processUserData({ name, hobbies }, [firstHobby]) {
console.log(`${name}의 취미는 ${hobbies.join(', ')}이고, 첫 번째 취미는 ${firstHobby}입니다.`);
}
const user = { name: 'Alice', hobbies: ['등산', '요리'] };
const hobbies = ['독서', '게임'];
processUserData(user, hobbies); //Alice의 취미는 등산, 요리이고, 첫 번째 취미는 독서입니다.
정리하며
ES6의 구조 분해 할당은 복잡한 데이터 구조를 해체하여 간편하게 변수에 할당하는 강력한 도구입니다.
중첩된 구조, 나머지 요소, 함수 반환값과 함께 사용하여 더욱 유용하게 활용할 수 있습니다.
참고 출처
- MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment