최근 추가된 JavaScript 문법으로 optional chaining은 객체를 검증할 때 사용된다.
평소에 object에 접근할 때 해당 값이 없을 때 항상 오류를 발생하는 경우가 많다.
이럴 때는 에러가 발생해서 멈추지 않고 단순 undefined를 리턴하는 값을 출력해주는 optional chaining을 이용하자
// optional chaining
object?.key // object가 비어있다면(null,undefined) key값을 가져오지 않음 (조건부)
이 문법이 생기기 전에는 이러한 오류를 사전에 검증하기 위해 조건문에 AND(&&)를 사용해서 객체가 있는지 , 객체의 키값이 있는지 확인 했지만 optional chaining으로 더욱 간결하게 작성할 수 있게 되었다. (reference error 없이 안전하게 값을 가져올 수 있다.)
ex)
const company = {
greeting : 'hello',
employee : {
superior : 'john',
subordinate : 'james'
}
}
console.log(company.greeting + company.employee.superior.boss.cto);
// undefined.cto
// Uncaught TypeError: Cannot read properties of undefined (reading 'cto')
console.log(company.greeting + company.employee.superior.boss?.ceo);
// helloundefined
ex)
document.querySelector('#name')?.innerHTML // undefined (에러를 감추는 문법)
ex)
console.log(undefined ?? '대신 이것을 출력');
// ??의 왼쪽이 undefined,null 이면 ??의 오른쪽을 출력