들어가며: 왜 구조 분해 할당이 필요할까?

자바스크립트로 개발하다 보면 API 응답이나 복잡한 설정 객체를 다룰 일이 정말 많죠. 예전에는 배열이나 객체의 값을 하나씩 꺼내 변수에 할당하는 반복적인 코드를 작성해야 했습니다.

// 옛날 방식: 하나씩 꺼내기
const theArray = [ false, true, false ];
const firstElement = theArray[0];
const secondElement = theArray[1];
const thirdElement = theArray[2];

이렇게 하면 변수 선언만 세 줄, 게다가 배열 인덱스를 일일이 써줘야 해서 실수하기 쉽고 가독성도 떨어집니다. ES6(ECMAScript 2015)에서 도입된 **구조 분해 할당(Destructuring Assignment)**은 이런 번거로움을 단번에 해결해줍니다.

// 구조 분해 할당: 한 줄로 끝!
const [ firstElement, secondElement, thirdElement ] = theArray;

이 글에서는 구조 분해 할당의 기본 문법부터 실무에서 유용하게 써먹을 수 있는 고급 패턴까지, 실제 코드로 하나씩 살펴보겠습니다. 원문은 CSS-Tricks의 JavaScript for Everyone 강의에서 발췌한 내용을 바탕으로 재구성했습니다.

Developer writing JavaScript destructuring code on laptop in modern office Coding Session Visual

배열 구조 분해: 기본기 다지기

배열을 분해할 때는 대괄호([])를 사용합니다. 각 변수는 배열의 인덱스 순서대로 값이 할당됩니다.

const theArray = [ false, true, false ];
const [ firstElement, secondElement, thirdElement ] = theArray;

console.log( firstElement );  // false
console.log( secondElement ); // true
console.log( thirdElement );  // false

특정 요소 건너뛰기

쉼표만 남기고 변수명을 생략하면 해당 인덱스의 값을 건너뛸 수 있습니다.

const theArray = [ true, false, true ];
const [ firstElement, , thirdElement ] = theArray;

console.log( firstElement ); // true
console.log( thirdElement ); // true (두 번째 요소는 건너뜀)

기본값 설정하기

분해 대상 배열에 해당 인덱스의 값이 없거나 undefined인 경우 기본값을 지정할 수 있습니다.

const theArray = [ true, undefined ];
const [ firstElement, secondElement = "기본 문자열", thirdElement = 100 ] = theArray;

console.log( secondElement ); // "기본 문자열"
console.log( thirdElement );  // 100

객체 구조 분해: 키 이름으로 값 꺼내기

객체를 분해할 때는 중괄호({})를 사용합니다. 변수 이름은 객체의 속성 키와 일치해야 합니다.

const theObject = {
  "theProperty" : true,
  "theOtherProperty" : false
};

const { theProperty, theOtherProperty } = theObject;

console.log( theProperty );       // true
console.log( theOtherProperty );  // false

다른 변수명으로 할당하기

속성 키와 다른 이름의 변수에 값을 할당하고 싶다면 키: 새변수명 문법을 사용합니다.

const theObject = {
  "theProperty" : true,
  "theOtherProperty" : false
};

const { theProperty : theIdentifier, theOtherProperty : theOtherIdentifier } = theObject;

console.log( theIdentifier );      // true
console.log( theOtherIdentifier ); // false

할당 패턴 vs 바인딩 패턴

구조 분해 할당에는 두 가지 방식이 있습니다.

바인딩 패턴 (Binding Pattern)

let이나 const로 변수를 선언하면서 동시에 분해하는 방식입니다. 가장 일반적이고 간결합니다.

const theArray = [ true, false ];
const [ theFirstIdentifier, theSecondIdentifier ] = theArray;

할당 패턴 (Assignment Pattern)

이미 선언된 변수에 값을 할당할 때 사용합니다. 특히 기존 배열이나 객체의 특정 위치에 값을 재할당할 때 유용합니다.

const theArray = [ true, false ];
let theFirstIdentifier;
let theSecondIdentifier;

[ theFirstIdentifier, theSecondIdentifier ] = theArray;

할당 패턴의 진가는 배열 요소 순서 바꾸기 같은 작업에서 드러납니다. 바인딩 패턴으로는 중복 선언 에러가 발생하는 경우도 할당 패턴으로 깔끔하게 해결됩니다.

const theArray = [ true, false ];
let theResultArray = [];

[ theResultArray[1], theResultArray[0] ] = theArray;

console.log( theResultArray ); // [ false, true ] (순서가 뒤바뀜)

객체에서 할당 패턴을 사용할 때는 주의할 점이 있습니다. 중괄호가 블록 문(block statement)으로 해석되지 않도록 괄호로 감싸줘야 합니다.

const theObject = {
  "theProperty" : true,
  "theOtherProperty" : false
};

let theProperty;
let theOtherProperty;

// 괄호로 감싸지 않으면 SyntaxError!
({ theProperty, theOtherProperty } = theObject );

할당 패턴을 사용하면 객체의 특정 속성들을 다른 객체의 속성으로 바로 매핑할 수도 있습니다.

const theObject = {
  "theProperty" : true,
  "theOtherProperty" : false
};

let resultObject = {};

({ theProperty : resultObject.resultProp, theOtherProperty : resultObject.otherResultProp } = theObject );

console.log( resultObject );
// { resultProp: true, otherResultProp: false }

Screenshot of JavaScript code showing destructuring assignment syntax

중첩 데이터 구조 분해: 실무에서 가장 많이 쓰는 패턴

실제 프로젝트에서는 객체 안에 객체, 배열 안에 객체 등 복잡한 구조의 데이터를 자주 다루게 됩니다. 구조 분해 할당은 이런 중첩 구조도 한 줄로 깔끔하게 풀어냅니다.

const theObject = {
  "theProperty" : true,
  "theNestedObject" : {
    "anotherProperty" : true,
    "stillOneMoreProp" : "A string."
  }
};

// 중첩 객체도 한 번에 분해!
const { theProperty, theNestedObject : { anotherProperty, stillOneMoreProp } } = theObject;

console.log( stillOneMoreProp ); // "A string."

객체 배열도 마찬가지입니다.

const theObject = [{
  "aProperty" : true,
},{
  "anotherProperty" : "A string."
}];

const [{ aProperty }, { anotherProperty }] = theObject;

console.log( anotherProperty ); // "A string."

Rest Properties: 나머지 값을 한 번에 잡아내기

분해하고 남은 나머지 요소들을 하나의 배열이나 객체로 모으고 싶다면 rest property(...)를 사용합니다.

const theArray = [ false, true, false, true, true, false ];
const [ firstElement, secondElement, ...remainingElements ] = theArray;

console.log( remainingElements );
// [ false, true, true, false ]

객체에서도 똑같이 동작합니다. 실제 API 응답 데이터를 다룰 때 매우 유용합니다. 아래는 뉴스레터 포스트 데이터 예시입니다.

const firstPost = {
  "id": "mat-update-1.md",
  "slug": "mat-update-1",
  "body": "안녕하세요, 여러분. 저는 Mat입니다.",
  "data": {
    "title": "Meet your Instructor",
    "pubDate": "2025-05-08T09:55:00.630Z",
    "headingSize": "large",
    "showUnsubscribeLink": true,
    "stream": "javascript-for-everyone"
  }
};

// title만 따로 빼고, 나머지 data 속성들은 metaData로 묶기
const { data : { title, ...metaData }, body } = firstPost;

console.log( title );    // "Meet your Instructor"
console.log( metaData );
// { pubDate: "2025-05-08T09:55:00.630Z", headingSize: "large", showUnsubscribeLink: true, stream: "javascript-for-everyone" }

이렇게 하면 API에서 어떤 추가 속성이 내려오든 metaData 객체에 모두 담아 유연하게 대응할 수 있습니다.

주의사항 및 한계

  1. null이나 undefined는 분해할 수 없습니다. 분해 대상이 null이나 undefinedTypeError가 발생하므로, 옵셔널 체이닝(?.)이나 기본값 처리를 함께 사용하는 것이 좋습니다.

  2. 중첩 분해는 가독성을 해칠 수 있습니다. 3단계 이상 깊이 들어가면 오히려 코드 이해가 어려워집니다. 적절히 분리해서 사용하세요.

  3. 성능: 일반적인 속성 접근과 비교해 미미한 차이는 있지만, 대부분의 애플리케이션에서 병목이 될 정도는 아닙니다.

Developer workspace with multiple monitors displaying JavaScript code and documentation Dev Environment Setup

실무 적용 팁 및 마무리

구조 분해 할당은 특히 다음과 같은 상황에서 빛을 발합니다.

  • React/Vue 컴포넌트에서 props나 state를 꺼낼 때
  • API 응답 데이터를 가공할 때
  • 설정 객체에서 필요한 값만 추출할 때
  • 함수 매개변수로 객체를 받을 때 (매개변수 자리에서 바로 분해)
// 함수 파라미터에서 바로 분해
function printUser({ name, age, ...rest }) {
  console.log(`${name} (${age}세)`);
  // rest에는 다른 추가 속성들이 들어있음
}

한국 개발 환경에서도 구조 분해 할당은 이미 표준처럼 사용되고 있습니다. 특히 TypeScript와 함께 사용하면 타입 안정성까지 확보할 수 있어 더욱 강력합니다.

다음 단계 학습 방향:

  • 구조 분해 할당과 함께 자주 쓰이는 **스프레드 연산자(Spread Operator)**도 함께 학습해보세요.
  • TypeScript의 타입 추론과 결합하면 더욱 강력한 패턴을 만들 수 있습니다.
  • 실제 오픈 소스 프로젝트(React, Vue, Lodash 등)의 소스 코드를 읽으면서 구조 분해 할당이 어떻게 사용되는지 분석해보는 것도 좋은 방법입니다.

자바스크립트 구조 분해 할당은 처음에는 낯설 수 있지만, 익숙해지면 코드를 훨씬 간결하고 표현력 있게 만들어줍니다. 오늘 배운 패턴들을 직접 코드에 적용해보면서 감을 익혀보세요!


함께 보면 좋은 글

본 콘텐츠는 신뢰할 수 있는 출처를 바탕으로 AI 도구를 활용하여 초안이 작성되었으며, 편집자의 검토를 거쳐 발행되었습니다. 전문가의 조언을 대체하지 않습니다.