배열이나 객체의 속성을 해체해여 그 값을 개별 변수에 담을 수 있게하는 javascript 표현식이다.
구조 분해 할당을 사용하면 코드가 간결해지고, 변수 선언과 할당을 하나의 표현식으로 처리할 수 있어 코드의 가독성과 유지보수성이 높아진다. 특히, 리액트 컴포넌트에서 props나 state를 다룰 때 매우 유용하게 사용된다.
배열의 요소를 개별 변수에 할당할 수 있다.
const array = [1, 2, 3];
// 배열 요소를 변수에 할당
const [first, second, third] = array;
console.log(first); // 출력: 1
console.log(second); // 출력: 2
console.log(third); // 출력: 3
필요한 요소만 선택적으로 할당할 수도 있다.
const array = [1, 2, 3, 4, 5];
const [first, , third, , fifth] = array;
console.log(first); // 출력: 1
console.log(third); // 출력: 3
console.log(fifth); // 출력: 5
객체의 속성을 변수에 개별적으로 할당할 수 있다.
const person = {
name: "John",
age: 30,
city: "New York"
};
// 객체 속성을 변수에 할당
const { name, age, city } = person;
console.log(name); // 출력: John
console.log(age); // 출력: 30
console.log(city); // 출력: New York
함수의 매개변수로 전달된 객체나 배열을 구조 분해 할당할 수 있다. 이는 특히 리액트 컴포넌트에서 자주 사용된다.
// 객체 매개변수 구조 분해
function displayPerson({ name, age, city }) {
console.log(`Name: ${name}, Age: ${age}, City: ${city}`);
}
const person = {
name: "John",
age: 30,
city: "New York"
};
displayPerson(person); // 출력: Name: John, Age: 30, City: New York
구조 분해 할당을 할 때 기본값을 설정할 수 있다. 기본값은 할당된 값이 undefined일 때만 사용된다.
const person = {
name: "John"
};
// 기본값 설정
const { name, age = 25, city = "Unknown" } = person;
console.log(name); // 출력: John
console.log(age); // 출력: 25
console.log(city); // 출력: Unknown