JavaScript에서 구조 분해 할당 (초급부터 고급까지)

발행: (2026년 3월 26일 PM 06:36 GMT+9)
3 분 소요
원문: Dev.to

Source: Dev.to

Without Destructuring

const user = {
  name: "John",
  age: 20,
  city: "Mumbai"
};

const name = user.name;
const age = user.age;
const city = user.city;

console.log(name, age, city);

With Destructuring

const user = {
  name: "John",
  age: 20,
  city: "Mumbai"
};

const { name, age, city } = user;

console.log(name, age, city);

Object Destructuring

Basic Assignment

const user = { name: 'Alice', age: 25 };
const { name, age } = user; // name = 'Alice', age = 25

Renaming

const user = { name: 'Alice' };
const { name: userName } = user; // userName = 'Alice'

Default Values

const user = {};
const { city = 'Unknown' } = user; // city = 'Unknown'

Nested Destructuring

const profile = { id: 1, info: { email: 'a@ex.com' } };
const { info: { email } } = profile; // email = 'a@ex.com'

Array Destructuring

Basic Assignment

const colors = ['red', 'blue', 'green'];
const [first, second] = colors; // first = 'red', second = 'blue'

Skipping Values

const colors = ['red', 'blue', 'green'];
const [first, , third] = colors; // first = 'red', third = 'green'

Swapping Variables

let a = 4;
let b = 5;

[a, b] = [b, a]; // a = 5, b = 4

How it works

  1. 오른쪽 배열 [b, a]가 먼저 평가되어 [5, 4]가 생성됩니다.
  2. 왼쪽의 구조분해 할당 [a, b] = [5, 4]가 실행되어 a = 5b = 4가 할당됩니다.

Rest Operator

const numbers = [1, 2, 3, 4];
const [one, ...others] = numbers; // one = 1, others = [2, 3, 4]

Important Points of Destructuring

  • 구조분해 할당은 원본 객체나 배열을 수정하지 않으며, 값만 추출합니다.
  • 얕은 복사를 생성합니다. 중첩된 객체나 배열은 여전히 원본 데이터를 가리키는 참조입니다.
const user = {
  name: "Abhi",
  address: {
    city: "Jalandhar"
  }
};

const { address } = user;
address.city = "Delhi";

console.log(user.address.city); // Delhi (original also changed)
  • null이나 undefined에 대해 구조분해 할당을 시도하면 TypeError가 발생합니다.
const { name } = null; // TypeError

Conclusion

JavaScript(ES6에서 도입)에서 구조분해 할당은 객체와 배열에서 값을 추출하기 위한 간결한 문법을 제공하여 가독성을 높이고 반복 코드를 줄여줍니다. 이름 바꾸기, 기본값, 중첩 구조, 나머지 연산자 지원은 물론 임시 변수 없이도 우아하게 변수 교환을 할 수 있습니다.

0 조회
Back to Blog

관련 글

더 보기 »

j.s에서 looping이란 무엇인가

JavaScript에서 루프는 같은 코드를 반복해서 작성하지 않고도 동일한 작업을 계속 수행하고 싶을 때 유용합니다. 유형…

JavaScript란 무엇인가? (초보자 친화적인 개요)

만약 당신이 웹사이트에서 버튼을 클릭했을 때 마법 같은 일이 일어난 적이 있다면—예를 들어 팝‑업이 나타나거나, 폼이 검증되거나, 페이지를 새로 고치지 않고 콘텐츠가 업데이트되는 등—