본문 바로가기
Programming/Javascript

[JS] 구조 분해 할당(Destructuring Assignment)이란?

by 기도메타 2025. 1. 6.

구조 분해 할당(Destructuring Assignment)은 배열이나 객체의 속성을 해체하여 개별 변수에 담을 수 있게 하는 JavaScript의 강력한 표현식입니다.

1. 배열 구조 분해

1-1) 기본 할당
배열의 요소들을 순서대로 새로운 변수에 할당할 수 있습니다:

const colors = ["green", "blue", "purple"];
const [c1, c2, c3] = colors;
console.log(c1); // "green"
console.log(c2); // "blue"
console.log(c3); // "purple"



1-2) 선언 분리 할당
변수 선언과 할당을 분리하여 구조분해를 할 수 있습니다:

let a, b;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

만약, 변수를 추가하고 싶을 때는 할당할 배열 내에 들어갈 자리가 있어야 한다. 없는 경우  undefined이 출력된다. 

let arr ['a','b','c'];
let [one, two, three, four='d'] = arr;
console.log(one,two,three,four);  //a,b,c,d

 


2. 객체 구조 분해

2-1) 기본 할당
객체의 속성을 변수로 분해할 수 있습니다:

const user = {
    id: 42,
    isVerified: true
};
const { id, isVerified } = user;
console.log(id); // 42
console.log(isVerified); // true



2-2) 새로운 변수명 할당
객체의 속성을 다른 이름의 변수로 할당할 수 있습니다:

const o = { p: 42, q: true };
const { p: foo, q: bar } = o;
console.log(foo); // 42
console.log(bar); // true

 

반응형