구조분해할당 (destructuring)

wonkeunC·2021년 4월 2일
0

JavaScript

목록 보기
5/15
post-thumbnail

구조분해할당 destructuring 이란?

Object, Array 등 그 외 요소들 안의 변수를 바깥으로 끄집어 내서 사용할 수 있도록 하는 것.

Object Destructuring (객체)

예시 1

// if() 에 settings 객체(object) 안에 있는 unfollow: 의 값을 가지고 오고 싶을때! 

if(settings.notification.unfollow) {

} 

// 이 코드는 문제점이 있다!
1. settings.notification.unfollow 는 보기에 좋지 않음.
2. unfollow의 값이 없을 수도 있다! 그러면 대부분 undefined 출력

🧩 destructuring 사용하기!

1. const {notification : 에 접근하고,
2. 최종적으로 접근하고 싶은 {unfollow} 의 값을 지정하며,
3. 마지막으로 } = settings; 으로 가장 부모인 값을 설정한다.

❗️여기서 const { notification : 은 변수가 아니다! 
  consoel.log(notification); 을 하면 undefined 가 출력된다. 
  이 경우는 {notification} 안에 있는 : {unfollow}의 값을 가져온 것이다.
  
❗️notification의 값을 가져오려면  
  const {notification} = settings; 이렇게 해줘야 한다. 

🧩 destructuring 값 여러개 가져오기

notification : { } 안에 있는 값들과 동시에 color : { } 의 값도 가져오고 싶다면!

결론은!
객체 object의 특정 값에 접근하기 위해 settings.notification ... 을 하는 것 보다
const { notification } = settings; 로 destructuring 처리 해주는 것이 지금 처럼 object를 다룰때 정말 유용하다. 삶의 질을 개선해 줄 정도이다.


🧩 destructuring 객체 안의 특정 값 변경하기


🧩 destructuring one-line-statement

notifications 객체가 통채로 없다면 !

const settings = {
     // notifications : { }  <- 에 대한 정보가 없다면!
}

profile
개발자로 일어서는 일기

0개의 댓글