[JavaScript] 구조 분해 할당

jjee·2025년 9월 22일

JavaScript

목록 보기
11/12
post-thumbnail

구조 분해 할당

JavaScript의 구조분해할당에 대해 알아보자

구조 분해 할당이란?

객체나 배열을 변수로 분해할 수 있도록 하는 문법이다.
함수의 매개변수가 많거나 매개변수의 기본값이 필요한 경우에도 사용할 수 있다.

배열 분해

배열에서 구조 분해 할당을 사용해보자.

기존 방법

const nameArray = ["Gildong", "Hong"];

const firstName = nameArray[0];
const surname = nameArray[1];

console.log(firstName); // "Gildong"
console.log(surname);   // "Hong"

기존의 배열의 값을 변수로 가져오는 방법이다.
배열의 위치값(index)를 사용해서 배열에 하나씩 값을 넣어야 한다.

구조 분해 할당

const nameArray = ["Gildong", "Hong"];

// 구조 분해 할당
const [firstName, surname] = nameArray;

console.log(firstName); // "Gildong"
console.log(surname);   // "Hong"

배열의 인덱스로 접근하지 않더라도 손쉽게 값을 변수에 할당할 수 있다.

값 무시하기 (ignore)
const nameArray = ["Anna", "Elice", "Moana"];

// 구조 분해 할당
const [first, , last] = nameArray;

console.log(first); // "Anna"
console.log(last);  // "Moana"

만약 필요하지 않은 요소가 있다면 쉼표(,)를 사용해서 넘길 수 있다.

기본값 할당
const nameArray = ["Anna", "Elice", "Moana"];

// 구조 분해 할당
const [first, more = "Hong"] = nameArray;

console.log(first); // "Anna"
console.log(more);  // "Hong"

변수에 기본 값을 작성하여 값이 없는 경우를 대비할 수 있다.
단, undefined 값인 경우에만 적용된다.
만약 값이 null이라면 null 값이 그대로 변수에 담긴다.

나머지 요소(rest)
const nameArray = ["Anna", "Elice", "Moana", "Hong", "Gang"];

// 구조 분해 할당
const [first, ...rest] = nameArray;

console.log(first); // "Anna"
console.log(rest);  // ["Elice", "Moana", "Hong", "Gang"]

...rest를 이용해서 나머지 요소를 한 배열에 담을 수 있다.

중첩 구조 분해 (nested destructuring)
const numbers = [1, [2, 3], 4];
const [one, [two, three], four] = numbers;

console.log(one, two, three, four); // 1 2 3 4

중첩된 값도 손쉽게 가져올 수 있다.

변수 값 교환하기 (swap trick)
let a = 1;
let b = 2;

[a, b] = [b, a];
console.log(a, b); // 2 1

가변 변수에서도 구조분해를 사용할 수 있다.

문자열 분해
const [a, b, c] = "ABC";
console.log(a, b, c); // "A" "B" "C"

문자열도 구조 분해 할당을 이용하여 분해가 가능하다.
숫자도 분해가 가능하다.

객체 분해

객체에서 구조 분해 할당을 사용해보자.

기존 방법

const profile = {
  name: "Hong",
  age: 28,
  job: "doctor"
};

// 구조 분해 할당
const name = profile.name;
const age = profile.age;
const job = profile.job;

console.log(name); // "Hong"
console.log(age);  // 28
console.log(job);  // "doctor"

기존의 객체의 값을 변수로 가져오는 방법이다.
객체 값의 속성을 이용하여 하나씩 값을 가져와야 한다.

구조 분해 할당

const profile = {
  name: "Hong",
  age: 28,
  job: "doctor"
};

// 구조 분해 할당
const {name, age, job} = profile;

console.log(name);   // "Hong"
console.log(age);    // 28
console.log(job);    // "doctor"

속성 값을 일일이 접근하여 가져오지 않아도 한 번에 가져올 수 있다.

값 무시하기 (ignore)
const profile = {
  name: "Hong",
  age: 28,
  job: "doctor"
};

// 구조 분해 할당
const {job, name} = profile;

console.log(name);   // "Hong"
console.log(job);    // "doctor"

필요한 값만 가져올 수 있으며, 가져오는 값의 순서가 바뀌더라도 문제 없다.

기본값 할당
const profile = {
  name: "Hong",
  age: 28,
  job: "doctor"
};

// 구조 분해 할당
const {name, height = 180} = profile;

console.log(name);   // "Hong"
console.log(height); // 180

기본값을 작성하여 값이 없는 경우를 대비할 수 있다.

객체에서 속성 이름 바꾸기 (aliasing)
const profile = {
  name: "Hong",
  age: 28,
  job: "doctor"
};

// 구조 분해 할당
const {name: n, height: h = 180} = profile;

console.log(n);   // "Hong"
console.log(h); // 180

변수명에 콜론(:)을 이용해서 변수명을 다르게 가져올 수도 있다.

나머지 요소(rest)
const profile = {
  name: "Hong",
  age: 28,
  job: "doctor"
};

const { name, ...rest } = profile;

console.log(name); // "Hong"
console.log(rest); // { age: 28, job: "doctor" }

...rest를 이용해서 나머지 요소를 한 객체에 담을 수 있다.

중첩 구조 분해 (nested destructuring)
const person = {
  name: "Anna",
  address: {
    city: "Seoul"
  }
};
const { address: { city } } = person;

console.log(city); // "Seoul"

중첩된 값도 손쉽게 가져올 수 있다.

만약 값이 없을 경우 undefined 오류 방지를 사용하기 위해서 기본값(= {})을 활용할 수도 있다.

const person = {};
const { address: { city } = {} } = person;

console.log(city); // undefined (오류 발생 안 함)

함수 매개변수 분해

함수의 매개변수에서 구조 분해 할당을 사용해보자.

기존 방법

function greet(user) {
  console.log(`${user.name} is ${user.age} years old`);
}

greet({ name: "Hong", age: 28 });

기존의 함수 매개변수 값을 가져오는 방법이다.
매개변수 값의 속성을 닷(.)을 이용해서 가져와 사용한다.

구조 분해 할당

function greet({ name, age }) {
  console.log(`${name} is ${age} years old`);
}

greet({ name: "Hong", age: 28 }); // "Hong is 28 years old"

구조 분해 할당을 이용하여 필요한 값의 속성명을 가져와서 사용할 수 있다.

기본값 할당
function greet({ name = "Guest", age = 0 } = {}) {
  console.log(`${name} is ${age} years old`);
}

greet(); // "Guest is 0 years old"

기본값을 작성하여 값이 없는 경우를 대비할 수 있다.

참고

profile
내가 나에게 알려주는 개발 공부

0개의 댓글