옵셔널 체이닝 ?.

한별·2023년 11월 5일

Javascript

목록 보기
6/25
post-thumbnail

?. 이 녀석의 이름은 Optional Chaining이다.

얘를 이용하면 undefined 또는 null의 속성에 접근하려고 할 때 error를 발생시키는 대신 undefined를 return하게 할 수 있다.

undefined?.props // undefined
null?.props // undefined

이건 왜 사용하는거지?

Nullish인 값의 속성을 조회하면 에러가 뜨는 것은 다들 알 것이다.

undefined.props
null.props
// TypeError: Cannot read properties of null

이 에러는 보통 api 호출로 가져온 데이터의 속성을 조회할 때 많이 발생한다.

/*
  아이디가 1인 user를 fetch해서
  이름과 나이를 보여주는 코드
*/
(async function () {
  const user = await fetch("http://example.com/users/1")
    .then((res) => res.json())
    .catch((err) => {
      console.error(err);
      return null;
    }); // user === null

  console.log(user.name, user.age); // Error!!
})();

위 코드는 fetch에서 오류가 발생하기 때문에 user 값은 null이 되고 user.nameuser.age에서 오류가 발생할 것이다.


Optional Chaining을 알기 전에는 if를 이용하여 에러를 고쳤을 것이다.

if(user) console.log(user.name, user.age);

하지만 Optional Chaining을 이용하여 수정할 수도 있다.

console.log(user?.name, user?.age);
profile
글 잘 쓰고 싶어요

0개의 댓글