[모딥다] 36장. 디스트럭처링 할당

vanLan·2026년 2월 25일

모딥다

목록 보기
23/25
post-thumbnail

36장. 디스트럭처링 할당

  • 구조화된 배열과 같은 이터러블 또는 객체를 destructuring(비구조화, 구조 파괴)하여 1개 이상의 변수에 개별적으로 할당하는 것.
  • 배열과 같은 이터러블 또는 객체 리터럴에서 필요한 값만 추출하여 변수에 할당할 때 유용.

📁 배열 디스트럭처링 할당

  • 대상은 이터러블 이어야 하며, 할당 기준은 배열의 인덱스임.

    const arr = [1, 2, 3];
    
    const [one, two, three] = arr;
    console.log(one, two, three);  // 1 2 3
  • 우변에 이터러블을 할당하지 않으면 에러 발생.

    const [x, y];  // SyntaxError: Missing initializer in destructuring declaration
    const [a, b] = {};  // TypeError: {} is not iterable
  • 배열 디스트럭처링 할당의 기준은 배열 인덱스이므로, 변수의 개수와 이터러블의 요소 개수가 반드시 일치할 필요 X.

    const [a, b] = [1, 2];
    console.log(a, b);  // 1 2
    
    const [c, d] = [1];
    console.log(c, d);  // 1 undefined
    
    const [e, f] = [1, 2, 3];
    console.log(e, f);  // 1 2
  • 배열 디스트럭처링 할당을 위한 변수에 기본값 설정 가능.

    // 기본값
    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 요소
    const [x, ...y] = [1, 2, 3];
    console.log(x, y);  // 1 [2, 3]

📁 객체 디스트럭처링 할당

  • 대상은 객체이어야 하며, 할당 기준은 프로퍼티 키임.

    const user = { firstName: 'HyounSeok', lastName: 'Kim' };
    
    const { lastName, firstName } = user;
    console.log(firstName, lastName);  // HyounSeok Kim
  • 우변에 객체 또는 객체로 평가될 수 있는 표현식을 할당하지 않으면 에러 발생.

    const { lastName, firstName };  // SyntaxError: Missing initailizer in destructuring declaration
    
    const { lstName, firstName } = null;  // TypeError: Cannot destructure propery 'lastName' of 'null' as it is null.
  • 객체의 프로퍼티 키와 다른 변수 이름으로 프로퍼티 값을 할당받으려면 다음과 같이 변수를 선언.

    const user = { firstName: 'HyounSeok', lastName: 'Kim' };
    
    const { lastName: ln, firstName: fn } = user;
    console.log(fn, ln);  // HyounSeok Kim
  • 변수에 기본값 설정 가능.

    const { lastName, firstName = 'HyounSeok' } = { lastName: 'Kim' };
    console.log(firstName, lastName);  // HyounSeok Kim
    
    const { lastName: ln, firstName: fn = 'HyounSeok' } = { lastName: 'Kim' };
    console.log(fn, ln);  // HyounSeok Kim
  • 중첩 객체일 경우 사용의 예:

    const user = {
      name: 'Lee',
      address: {
        zipCode: '03068',
        city: 'Seoul'
      }
    };
    
    const { address: { city } } = user;
    console.log(city);  // 'Seoul'
  • Rest 프로퍼티 사용.

    const { x, ...rest } = { x: 1, y: 2, z: 3 };
    console.log(x, rest);  // 1 { y: 2, z: 3 }
profile
프론트엔드 개발자를 꿈꾸는 이

0개의 댓글