본문 바로가기
IT 개발/자바스크립트

[JAVASCRIPT] 자바스크립트 비구조화 할당 (Destructuring Assignment)

by 이것 저것 모든것 2025. 2. 24.
728x90

자바스크립트 비구조화 할당 (Destructuring Assignment) 가이드

목차

  1. 개요
  2. 객체 비구조화 할당
  3. 배열 비구조화 할당
  4. 고급 기능
  5. 실제 사용 사례

개요

비구조화 할당은 ES6에서 도입된 문법으로, 배열이나 객체의 속성을 해체하여 개별 변수에 담을 수 있게 하는 자바스크립트 표현식입니다.

객체 비구조화 할당

기본 문법

const person = {
    name: '김철수',
    age: 25,
    job: '개발자'
};

const { name, age, job } = person;
console.log(name); // '김철수'
console.log(age);  // 25
console.log(job);  // '개발자'

새로운 변수명 할당

const { name: userName, age: userAge } = person;
console.log(userName); // '김철수'
console.log(userAge);  // 25

기본값 설정

const { name, age = 20, hobby = '없음' } = person;
console.log(hobby); // '없음'

배열 비구조화 할당

기본 문법

const numbers = [1, 2, 3, 4, 5];
const [first, second, third] = numbers;

console.log(first);  // 1
console.log(second); // 2
console.log(third);  // 3

나머지 요소 가져오기

const [head, ...tail] = numbers;
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]

값 건너뛰기

const [first, , third] = numbers;
console.log(first); // 1
console.log(third); // 3

고급 기능

중첩 객체 비구조화

const user = {
    info: {
        name: '이영희',
        address: {
            city: '서울',
            country: '한국'
        }
    }
};

const { info: { name, address: { city } } } = user;
console.log(name); // '이영희'
console.log(city); // '서울'

함수 매개변수 비구조화

function printUserInfo({ name, age, job = '무직' }) {
    console.log(`이름: ${name}`);
    console.log(`나이: ${age}`);
    console.log(`직업: ${job}`);
}

printUserInfo({ name: '박지성', age: 30 });
728x90

실제 사용 사례

React 컴포넌트에서의 사용

function UserProfile({ user, onUpdate, className }) {
    return (
        <div className={className}>
            <h2>{user.name}</h2>
            <button onClick={onUpdate}>정보 수정</button>
        </div>
    );
}

API 응답 처리

async function getUserData() {
    const response = await fetch('/api/user');
    const { id, name, email } = await response.json();

    return {
        userId: id,
        userName: name,
        userEmail: email
    };
}

모듈 임포트

import { useState, useEffect } from 'react';

주의사항

  1. 존재하지 않는 속성을 비구조화하면 undefined가 할당됩니다.
  2. 중첩된 객체의 경우, 중간 단계가 null 또는 undefined이면 오류가 발생할 수 있습니다.
  3. 배열 비구조화에서는 순서가 중요합니다.
  4. 객체 비구조화에서는 속성 이름이 일치해야 합니다.

참고사항

  • ES6 이상의 자바스크립트 환경에서 사용 가능합니다.
  • 브라우저 호환성을 확인하세요.
  • 트랜스파일러(Babel 등)를 사용하면 이전 버전의 자바스크립트에서도 사용할 수 있습니다.
728x90