JavaScript

[새로운 기능] Optional Chaining

  • -
반응형

 

Optional Chaining

Optional Chaining이란 값이 있을 경우에만 chaining 하는 방법이다. 

예를 들어 REST 요청을 통해서 전달받은 객체가 있는데 그 데이터의 속성이 있을 때와 없을 때가 있다면 값을 처리하기가 귀찮은 경우가 많다.

예를 들어 다음과 같은 users 배열을 생각해보자.

let users = [
  {name: "hong gil dong", email: {id: "hong", domain: "def.net"}}, 
  {name: "jang gil san"}
];

users의 첫 번째 객체는 name과 email 정보가 있고 두 번째 객체에는 name만 존재한다.

만약 반복문을 이용해 user 객체의 내용을 상세하게(email의 id, domain까지) 출력한다면 어떻게 될까?

users.forEach((user) => {
    console.log(user.name, user.email.id, user.email.domain);
});

결과는 caught TypeError: Cannot read properties of undefined (reading 'id') 오류가 발생한다. 두 번째 user의 경우 user.email 까지는 접근 가능하지만 user.email이 undefined이므로 undefined.id를 사용할 수는 없기 때문이다.

따라서 위 내용을 처리하려면 아래와 같이 3항 연산자를 사용해 볼 수 있다.

users.forEach((user) => {
    console.log(user.name, user.email ? user.email.id : undefined, 
                           user.email ? user.email.domain : "undefined");
});

이런 상황에서 사용해볼 수 있는 연산자가 optional chaining이다.

optional chaining은 ?를 이용해서 chaining을 진행하며 만약 속성이 undefined가 아니면 뒤쪽으로 chaining을 진행한다.

users.forEach((user) => {
    console.log(user.name, user.email?.id, user.email?.domain);
});

만약 속성의 이름이 특수문자를 포함하여 [ ]로 접근해야 하는 경우라면 . 를 삽입해서 호출한다.
 

user.addr["detail address"]='main street'

console.log(user.addr?.["detail address"))
반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.