[JavaScript] 구조 분해 할당

jjee·2025년 8월 21일

JavaScript

목록 보기
1/12

썸네일

구조 분해 할당(Destructuring assignment)

구조 분해 할당이란, ES6(ECMAScript 2015)에 도입된 기능으로
배열이나 객체의 값 또는 프로퍼티를 개별 변수에 쉽고 간결하게 할당하는 방법이다.

배열 구조 분해 할당

배열 구조 분해 할당은 배열의 요소를 순서대로 변수에 할당한다.

전체 값 가져오기

배열 안의 값의 개수만큼 변수를 작성하면 모든 값을 순서대로 가져올 수 있다.

let arr = [1, 2, 3];
let [a, b, c] = arr;

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

일부만 가져오기

쉼표(,)를 이용해서 변수를 작성하지 않고 건너뛰면 해당 순서의 값은 가져오지 않는다.

const fruits = ['apple', 'banana', 'orange', 'grape'];
const [,, thirdFruit, fourthFruit] = fruits;

console.log(thirdFruit);  // 'orange'
console.log(fourthFruit); // 'grape'

기본값 설정하기

변수에 기본값을 설정하여 값이 없을 경우 기본값을 넣을 수 있다.

const numbers = [10, 20];
const [x, y, z = 30] = numbers;

console.log(x); // 10
console.log(y); // 20
console.log(z); // 30 (기본값)

객체 구조 분해 할당

객체 구조 분해 할당은 객체의 속성들을 변수에 할당한다.
이때 변수명은 객체의 키와 동일해야 한다.

전체 값 가져오기

객체 내의 키를 모두 작성하여 모든 값을 가져올 수 있다.

const person = { name: 'Mike', age: 30 };
const { name, age } = person;

console.log(name); // "Mike"
console.log(age);  // 30

다른 변수 이름으로 가져오기

만약 변수의 이름을 키 값이 아닌 다른 값으로 하고 싶다면 콜론(:)을 사용하여 원하는 변수명을 입력할 수 있다.

const person = { name: 'Mike', age: 30 };
const { name: personName, age: personAge } = person;

console.log(personName); // 'Mike'
console.log(personAge);  // '30'

기본값 설정하기

배열과 마찬가지로 기본값을 설정할 수 있다.

const person = { name: 'Mike', age: 30 };
const { name: myName, age: myAge, country = '한국' } = person;

console.log(myName);    // 'Mike'
console.log(myAge);     // 30
console.log(country);   // '한국' (기본값)

중첩된 구조 분해 할당

객체나 배열이 중첩된 경우에도 구조 분해를 사용하여 깊숙한 곳의 값을 바로 꺼내올 수 있다.

중첩된 객체 분해

const user = {
  id: 101,
  info: {
    email: 'test@example.com',
    location: '서울'
  },
  preferences: ['darkMode', 'notifications']
};

// info 객체 안의 email과 location 속성을 바로 꺼냅니다.
const { id, info: { email, location } } = user;

console.log(id);       // 101
console.log(email);    // 'test@example.com'
console.log(location); // '서울'

중첩된 배열과 객체 조합 분해

const students = [
  { name: 'John', score: 90 },
  { name: 'Jane', score: 85 }
];

// 첫 번째 배열 요소의 name 속성만 꺼냅니다.
const [{ name: firstStudentName }] = students;

console.log(firstStudentName); // 'John'

구조 분해 할당의 장점

가독성 향상

코드가 간결해지고 가독성이 좋아진다.

생산성 향상

불필요한 변수 선언을 줄여 개발 시간을 단축한다.

유연성

특정 값만 추출하거나 기본값을 설정하는 등 다양한 방식으로 활용 가능하다.

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

0개의 댓글