
옵셔널 체이닝(.?)은 존재하지 않을 수 있는 객체 프로퍼티 또는 메서드를 안전하게 호출하는 문법
// syntax
object?.property
?.은 객체의 깊은 속성 값을 안전하게 접근할 수 있도록 도와준다.undefined를 반환한다.NOTE
프로퍼티가 없는 중첩 객체를 에러 없이 안전하게 접근할 수 있다.
.?앞의 평가 대상이undifined나null이면 평가를 멈추고undefined를 반환한다.
const food = {
breakfast: {
meal: 'apple',
desert: {
drink: 'juice',
},
},
lunch: {
drink: 'coffee',
meal: 'pasta',
},
};
console.log(food.lunch.desert.drink);
// Cannot read properties of undefined (reading 'drink')
food.lunch → 존재하므로 통과food.lunch.desert→ 존재 ❌,food.lunch.desert = undefined undefined.drink → undifined에는 drink 프로퍼티가 없으므로 에러 발생JS는 존재하지 않는 desert프로퍼티에서 drink를 읽으려고 하는 시점에 에러를 일으킨다.
Cannot read properties of undefined (reading 'drink')
const food = {
breakfast: {
meal: 'apple',
desert: {
drink: 'juice',
},
},
lunch: {
drink: 'coffee',
meal: 'pasta',
},
};
console.log(food.lunch.desert?.drink ?? "No drink found");
// Cannot read properties of undefined (reading 'drink')
food.lunch.desert가 undifined 이므로 ?.이후의 평가는 중단된다. No drink found가 반환됨 → 명시적 런타임 에러가 아닌 설정된 기본 값 불러오기 가능