본문 바로가기
코드잇 스프린트 6기/JS Q.R 스터디

[JS Q.R 스터디] 디스트럭처링 할당

by 학습하는 청년 2024. 4. 15.

최종 수정 : 2024-04-15

36장. 디스트럭처링 할당

디스트럭처링(destructuring assignment, 구조 분해 할당)은 구조화된 배열과 같은 이터러블 또는 객체를 destrcuturing(비구조화)하여 1개 이상의 변수에 개별적으로 할당하는 것을 말한다. 배열과 같은 이터러블 또는 객체 리터럴에서 필요한 값만 추출하여 변수에 할당할 때 유용하다.

 

1. 배열 디스트럭처링 할당

배열의 각 요소를 배열로부터 추출하여 1개 이상의 변수에 할당한다. 할당의 대상은 이터러블이어야 하며, 할당 기준은 배열의 인덱스다. 즉, 순서대로 할당된다.

const arr = [1, 2, 3];
const [one, two, three] = arr;

console.log(one, two, three); // 1 2 3

그러나 변수의 개수와 이터러블의 요소 개수가 반드시 일치할 필요는 없다.

const [c, d] = [1];
console.log(c, d); // 1 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

 

할당을 위한 변수에 기본값을 설정할 수 있다.

const [a, b, c = 3] = [1, 2];
console.log(a, b, c); // 1 2 3

const [e, f = 10, g = 3] = [1, 2];
console.log(e, f, g); //  1, 2, 3

 

Rest 파라미터와 유사하게 Rest 요소 ...을 사용할 수 있다. Rest 파라미터와 마찬가지로 반드시 마지막에 위치해야 한다.

const [x, ...y] = [1, 2, 3];
console.log(x, y); // 1 [2, 3]

 

 

2. 객체 디스트럭처링 할당

할당 기준은 프로퍼티 키다. 즉, 순서는 의미가 없으며 선언돈 변수 이름과 프로퍼티 키가 일치하면 할당된다.

const user = { firstName: 'YeongTaek', lastName: 'Oh' };

const { lastName, firstName } = user;
console.log(firstName, lastName); // Yeongtaek Oh

const { lastName, firstName } = { firstName: 'YeongTaek', lastName: 'Oh' };
// 위 아래는 동치다.
const { lastName, firstName} = user;
// 위 아래는 동치다.
const { lastName: lastName, firstName: firstName } = user;

 

객체에서 프로퍼티 키로 필요한 값만 추출하여 변수에 할당하고 싶을 때 유용하다.

const str = 'Hello';
// String 래퍼 객체로부터 length 프로퍼티만 추출
const { length } = str;
console.log(length); // 5

const todo = { id: 1, content: 'HTML', completed: true };
// todo 객체로부터 id 프로퍼티만 추출
const { id } = todo;
console.log(id); // 1

댓글