[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",
detailOption: {
name: "kim",
age: 30,
},
};

const getInformation = (person) => {
console.log(
  person.detailOption &&
person.detailOption.score &&
person.detailOption.score.third
);
};

getInformation(information1); // 50
getInformation(information2); // undefined


하지만 이렇게 작성할 경우 코드가 길어진다는 단점이 있다.

이때 사용하는것이 옵셔널 체이닝 이다.


const getInformation = (person) => {
console.log(person.detailOption.score?.third);
};


getInformation 함수안에 && 연산자로 작성했던것을 옵셔널 체이닝( ?. )를 사용하여 위처럼 간단히 작성할 수 있다.

이렇게 작성하게 되면 ?. 기호의 왼쪽에 위치하고있는 평가대상이 undefined 이거나 null 이면 평가를 멈추고 undefined를 반환한다.

위 코드에서 score가 ?. 를 만나 평가될때 undefined 이므로 더이상 뒤에 값을 평가하지 않고 undefined를 반환하게 된다.

그러므로 중첩 객체에 해당 프로퍼티값이 없더라도 오류가 발생하지않고 undefined를 반환하며 

&& (AND)연산자를 사용하여 길게 코드를 작성할 필요도 없어졌다.



요약하면 및 중요 포인트

옵셔널 체이닝을 아무렇게나 사용하면 안된다.

?. 는 존재하지 않아도 괜찮은 평가 대상에만 사용해야 한다.

위에 코드를 보면 detailOption은 반드시 존재해야하는 값이지만 score는 반드시 존재해야하는 값이 아니다.

그러므로 detailOption이 아닌 score에 사용하는 것이 맞게 사용하는 방법이다.

detaipOption?.score?.third 이렇게 모든 객체에 옵셔널 체이닝을 작성하게되면 오류 발생시 디버깅이 어려워질 수 있다.






댓글