하루 기록

[Javascript] 구조 분해 할당 본문

Today I Learned/in dev

[Javascript] 구조 분해 할당

떼굴펜 2024. 4. 22. 14:57

구조분해할당 예시

 

구조 분해 할당(destructuring)이란, 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.

 

(1) 배열일 때

배열에서 구조 분해 할당문을 아래와 같이 사용할 수 있습니다.

const [a, b, c] = ['value1', 'value2', 'value3'];

console.log(a);   // value1
console.log(b);   // value2
console.log(c);   // value3

 

 

만약 아래처럼 좌변 배열의 크기가 우변의 것보다 작을 때, undefined가 할당됩니다. 변수 d처럼 분해값이 undefined 일 때 대신 할당할 기본값을 셋팅할 수도 있습니다.

const array = [1, 2];
const [a, b, c, d = 7] = array;

console.log(a);   // 1
console.log(b);   // 2
console.log(c);   // undefined    > 만약 아래처럼 좌변 배열의 크기가 우변의 것보다 작을 때, undefined가 할당
console.log(d);   // 7                   > undefined 대신 기본값을 셋팅할 수 있습니다.

 

 

(2) 객체일 때

const user = { name : '떼굴펜', age : 20};
const {name : newName, age, gender, hasChild = false } = user;   
     // 변수 newName에 user.name의 값을 할당해줘
     // 변수 age에 user.age 값을  할당해줘
     // 변수 gender에 user.gender 값을  할당해줘
     // 변수 hasChild에 user.hasChild 값을 할당해줘, 만약 undefined라면 false값을 셋팅해줘

console.log(newName);   //  '떼굴펜'
console.log(age);             //  20
console.log(gender);        //  undefined
console.log(hasChild);     //  false

 

 

 

 

 

 

참고 link)

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment