배열 디스트럭처링 할당의 대상(할당문의 우변)은 이터러블이어야 하며, 할당 기준은 배열의 인덱스다.
const arr = [1, 2, 3];
const [one, two, three] = arr;
console.log(one, two, three); // 1,2,3
선언과 할당을 분리할 수도 있다. 단, 이 경우 const 키워드로 변수를 선언할 수 없다.
let [x, y];
[x, y] = [1, 2];
배열의 할당 기준은 배열의 인덱스이다. 이때 변수의 개수와 이터러블의 요소 개수가 반드시 일치할 필요는 없다.
let [a, b] = [1];
console.log(a, b); // 1 undefined
let [c, d] = [1, 2, 3];
console.log(c, d); // 1 2
let [e, f] = [1, , 3];
console.log(e, f); // 1 3
배열 디스트럭처링 할당을 위한 변수에 기본값을 설정할 수 있다. 이때 기본값보다 할당된 값이 우선한다.
const [a, b = 10, c = 3] = [1, 2];
console.log(a, b, c); // 1 2 3
배열 디스트럭처링 할당을 위한 변수에 Rest 파라미터와 유사하게 Rest요소 ...을 사용할 수 있다. Rest 요소는 Rest 파라미터와 마찬가지로 반드시 마지막에 위치해야 한다.
const [x, ...y] = [1, 2, 3];
console.log(x, y); // 1 [2, 3]
객체의 각 프로퍼티를 객체로부터 추출하여 1개 이상의 변수에 할당한다. 이때 객체 디스트럭처링 할당의 대상은 객체이어야 하며, 할당 기준은 프로퍼티 키다.
const user = { firstName: 'Ungmo', lastName: 'Lee' };
// 순서는 의미 없이 키를 기준으로 할당된다.
const { lastName, firstName } = user;
// 위와 아래는 동치다.
const { lastNmae: lastName, firstName: firstName } = user;
console.log(firstName, lastName); // Ungmo Lee
객체의 프로퍼티 키와 다른 변수 이름으로 프로퍼티 값을 할당받으려면 다음과 같이 변수를 선언한다.
const user = { firstName: 'Ungmo', lastName: 'Lee' };
const { lastName: ln, firstName: fn } = user;
console.log(fn, ln); // Ungmo Lee
객체 디스트럭처링 할당을 위한 변수에 기본값을 설정할 수 있다.
const { firstName: fn = 'Ungmo', lastName: ln } = { lastName: 'Lee' } ;
console.log(fn, ln); // Ungmo Lee
객체를 인수로 전달받는 매개변수에 객체 디스트럭처링 할당을 사용하면 좀 더 간단하고 가독성 좋게 표현할 수 있다.
function printTodo({ content, completed }){
console.log(`할일 ${content}은 ${completed ? '완료' : '비완료' } 상태입니다.`);
}
printTodo({ id: 1, content: 'HTML', completed: true }) // 할일 HTML은 완료 상태입니다.
배열의 요소가 객체인 경우 배열 디스트럭처링 할당과 객체 디스트럭처랑 할당을 혼용할 수 있다.
const todo = [
{ id: 1, content: 'HTML', completed: true },
{ id: 2, content: 'CSS', completed: false },
{ id: 3, content: 'JS', completed: false },
]
const [,{ id }] = todo;
console.log(id); // 2
중첩 객체의 경우는 다음과 같이 사용한다.
const user = {
name: 'Lee',
address: {
zipCode: '03068',
city: 'Seoul',
}
};
const { address: { city } } = user;
console.log(city); // 'Seoul'
Rest 파라미터와 유사하게 Rest 프로퍼티 ...을 사용할 수 있다.
const { x, ...rest } = { x: 1, y: 2, z: 3 };
console.log(x, rest); // 1 { y: 2, z: 3 }