Post

비구조화 할당

비구조화 할당

비구조화 할당 (Destructuring Assignment): JavaScript에서 객체와 배열을 더 똑똑하게 쓰는 법

1. 비구조화 할당이란?

비구조화 할당(Destructuring Assignment)은 객체나 배열에서 값을 추출해서 변수에 한 번에 할당하는 문법이다. ES6부터 도입되었고, 가독성과 코드의 간결함을 크게 높여준다.


2. 배열 비구조화

1
2
3
4
5
6
const arr = [1, 2, 3];
const [a, b, c] = arr;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

일부만 받을 수도 있음

1
2
const [first, , third] = [10, 20, 30];
console.log(third); // 30

나머지를 묶기 (Rest)

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

3. 객체 비구조화

1
2
3
4
5
6
7
8
9
const user = {
  name: "철수",
  age: 28
};

const { name, age } = user;

console.log(name); // 철수
console.log(age);  // 28

변수 이름 바꾸기

1
2
const { name: userName } = user;
console.log(userName); // 철수

기본값 할당

1
2
const { nickname = "익명" } = user;
console.log(nickname); // 익명

4. 함수 인자에서의 비구조화

1
2
3
4
5
6
function printUser({ name, age }) {
  console.log(`${name}${age}살`);
}

const user = { name: "영희", age: 22 };
printUser(user); // 영희은 22살

배열 인자도 가능

1
2
3
4
function sum([a, b]) {
  return a + b;
}
console.log(sum([3, 5])); // 8

5. 중첩 구조 비구조화

1
2
3
4
5
6
7
8
9
10
11
12
13
const user = {
  name: "민수",
  contact: {
    email: "minsu@example.com",
    phone: "010-1234-5678"
  }
};

const {
  contact: { email }
} = user;

console.log(email); // minsu@example.com

6. 실무 적용 예시

✅ Axios 응답 처리 시

1
2
3
4
axios.get("/api/user").then(({ data }) => {
  const { name, age } = data;
  console.log(name, age);
});

✅ React useState 훅

1
const [count, setCount] = useState(0);

✅ 배열 map에서 index 추출

1
2
3
items.map(([id, value], index) => {
  return `${index}: ${id}-${value}`;
});

7. 장점 요약

  • 코드 간결
  • 가독성 향상
  • 불필요한 변수 제거
  • 함수 매개변수 정리 효과

8. 결론

비구조화 할당은 modern JavaScript에서 기본 중의 기본이다. 코드를 간결하고 명확하게 만들어 주고, 특히 API 응답 처리, React, Node.js 등 실무 전반에서 매우 자주 쓰인다. 익숙해지는 건 필수다.

This post is licensed under CC BY 4.0 by the author.