디스트럭처링 할당 문법은 배열의 값 또는 객체의 속성을 풀어서 별개의 변수로 쓸 수 있게 해주는 자바스크립트 표현식이다.

객체 디스트럭처링

 
const person = {
	first: "Alberto",
	last: "Montalesi",
};
 
const {first, last} = person;
 

디스트럭처링을 이용하여 person이 가진 속성에 접근함과 동시에 해당 속성 이름으로 변수 선언이 가능함을 알 수 있다.

변수의 이름을 객체의 속성과 동일하게 지정하는 데 그치지 않고, 다음과 같이 변수 이름을 바꿀 수도 있다.

 
// person.links.social.facebook 프로퍼티를 찾아 fb라는 변수로 명명함
const {facebook: fb} = person.links.social;
 
console.log(fb);        // https://www.facebook.com/alberto.montalesi
console.log(facebook);  // ReferenceError: facebook is not defined
 

다음과 같이 기본값을 전달할 수도 있다.

 
// 변수를 fb로 다시 명명하고 기본값을 설정한다.
const {facebook: fb = "https://www.facebook.com"} = person.links.social;
 

배열 디스트럭처링

 
const person = ["Alberto", "Montalesi", 25];
const [name, surname, age] = person;
 

생성하려는 변수의 수가 배열의 수보다 적다면 오른쪽에서부터 남는 원소를 버린다.

나머지 모든 값을 얻고 싶다면 레스트 연산자 rest operator를 사용하면 된다.

 
const person = ["Alberto", "Montalesi", "pizza", "ice cream", "cheese cake"];
// 레스트 연산자를 사용하여 나머지 값 전체를 얻는다.
const [name, surname, ...food] = person;
// ["pizza", "ice cream", "cheese cake"]
console.log(food);
 

이 예에서 배열의 처음 두 값은 name과 surname에 할당되고 나머지 rest는 food 배열에 할당된다.

디스트럭처링을 이용하여 변수 교체

디스트럭처링 할당을 사용하면 변수의 값을 매우 쉽게 서로 교체할 수 있다.

 
let hungry = "yes";
let full = "no";
 
[hungry, full] = [full, hungry];
// no, yes
console.log(hungry, full);
 

참고자료

모던_자바스크립트_핵심_가이드