개발자취/JAVASCRIPT

Destructuring (구조 분해 할당) - JavaScript

까연 2022. 1. 26. 20:40

Destructuring "구조 분해 할당"


배열과 객체는 자바스크립트에서 많이 쓰이는 자료구조이며, 많이 쓰이는 배열이나 객체의 속성을 해체해서 그 값을 개별 변수에 담을 수 있게 하는 자바스크립트 표현식

 

 

ECMAScript(ES6)에서 이러한 Destructuring 문법을 제공한다.

다음은 Destructuring을 사용하는 방법이다.

 

배열 분해하기

let arr = [1,2,3]
let [first, second] = arr

console.log(first) // 1
console.log(second) //2

아래의 코드는 위의 코드와 같은 결과를 출력하는 코드

let first = arr[0]
let second = arr[1]

destructuring은 분해 대상이 수정되거나 없어지는 것은 아니다.

코드 실행에 차이는 없으며 요소들을 직접 변수에 할당하는 것보다 코드의 양이 줄어든다는 점만 다르다.

 

let arr = [1,2,3]
const [first, , second] = arr

console.log(first, second) // 1 3

특정 요소를 변수로 사용하지 않을 땐 콤마로 비워둔다.

 

 

 

객체 분해하기

const img = { name: 'test.jpg', options: { width: 200 } }

const { width } = img.options
console.log(width) // 200

객체의 키가 존재하지 않을 경우 변수의 값은 undefined가 저장된다.

const img = { name: 'test.jpg', options: { width: 200 } }

const { width, height } = img.options
console.log(width, height) // 200, undefined

객체의 키 값과 다른 변수명으로 저장하고 싶을 경우,

const img = { name: 'test.jpg', options: { width: 200 } }

const { width: imgWidth } = img.options
console.log(imgWidth) // 200