라벨이 ?.인 게시물 표시

[JavaScript] 옵셔널 체이닝 (optional chaining)

이미지
옵셔널 체이닝( ?. )을 사용하면 프로퍼티에 작성되지않은 중첩객체로 발생되는 에러를 해결할 수 있다. const information1 = { team : "A" , detailOption : { name : "lee" , age : 30 , score : { first : 10 , second : 30 , third : 50 , }, }, }; const information2 = { team : "C" , detailOption : { name : "kim" , age : 30 , }, }; const getInformation = ( person ) => { console . log ( person . detailOption . score . third ); }; getInformation 함수에 information1 을 전달하면 숫자 50을 반환하지만 getInformation 함수에 information2 을 전달하면 아래와 같이 오류를 반환한다. 에러 발생 원인은  information2 내부에 프로퍼티에 작성된 중첩객체 detailOption 내부의 프로퍼티에 작성된 score에 프로퍼티로 third가 작성되지 않았기 때문이다. 이렇게 오류가 발생할때 && (AND)연산자를 사용하여 아래와 같이 해결할 수 있었다. const information1 = { team : "A" , detailOption : { name : "lee" , age : 30 , score : { first : 10 , second : 30 , third : 50 , }, }, }; const information2 = { team : "C&qu