구조화된 배열과 같은 이터러블 또는 객체를 비구조화하여 1개 이상의 변수에 개별적으로 할당하는 것을 말한다.
const arr = [1, 2, 3];
const [one, two, three] = arr;
console.log(one, two, three); // 1 2 3
이때 우변에 이터러블을 할당하지 않으면 에러가 발생한다.
const [x, y]; // SyntaxError: Missing initializer in destructuring declaration
const [a, b] = {}; // TypeError: {} is not iterable
순서대로 할당되긴 하지만 변수의 개수와 이터러블 요소의 개수가 일치할 필요는 없다.
const [c, d] = [1];
console.log(c); // 1
console.log(d); // undefined
const [e, f] = [1, 2, 3];
console.log(e, f); // 1 2
const [g, , h] = [1, 2, 3];
console.log(g, h); // 1 3
배열 디스트럭처링 할당에 Rest 파라미터와 유사하게 Rest 요소(...)를 사용할 수 있다.
Rest 요소는 반드시 마지막에 위치해야 한다.
// Rest 요소
const [x, ...y] = [1, 2, 3];
console.log(x); // 1
console.log(y); // [ 2, 3 ]
객체를 디스트럭처링하여 변수에 할당하기 위해서는 프로퍼티 키를 사용해야 한다.
const user = { firstName: 'Ungmo', lastName: 'Lee' };
const { lastName, firstName } = user;
console.log(firstName); // Ungmo
console.log(lastName); // Lee
만약 프로퍼티 키와 다른 이름으로 변수에 할당하고 싶으면 다음과 같이 할당을 하면 된다.
const user = { firstName: 'Ungmo', lastName: 'Lee' };`
// 프로퍼티 키가 lastName인 프로퍼티 값을 ln에 할당하고,
// 프로퍼티 키가 firstName인 프로퍼티 값을 fn에 할당한다.
const { lastName: ln, firstName: fn } = user;
console.log(fn); // Ungmo
console.log(ln); // Lee
객체 디스트럭처링 할당은 객체를 인수로 전달받는 함수의 매개변수에도 사용할 수 있다.
function printTodo(todo) {
console.log(`할일 ${todo.content}은 ${todo.completed ? '완료' : '비완료'}`);
}
printTodo({ id: 1, content: 'HTML', completed: true });
// 할일 HTML은 완료
위와 같은 코드에서 todo 객체에서 { content, completed }를 디스트럭처링 할당하여 다음과 같이 바꿀 수 있다.
function printTodo({ content, completed }) {
console.log(`할일 ${content}은 ${completed ? '완료' : '비완료'}`);
}
printTodo({ id: 1, content: 'HTML', completed: true });
// 할일 HTML은 완료
해당 방법은 객체를 그대로 이용하는 것보다 가독성이 좋아서 권장된다.
const todos =[
{ id:1, content:"HTML" , completed:true },
{ id:2, content:"CSS" , completed:true },
{ id:3, content:"JS" , completed:false }
]
// todos 배열의 두 번째 요소인 객체로 부터 id 프로퍼티만 추출한다.
const [ , {id} ] = todos;
console.log(id) // 2
const user = {
name : "Lee",
address:{
Code : "03068",
city : "Seoul"
}
}
// address 프로퍼티 키로 객체를 추출하고 이 객체의 city 프로퍼티 키로 값을 추출한다.
const { address : { city } } = user;
const {city} = address;
console.log(city) // "Seoul"