자바스크립트 - 옵셔널 체이닝 ?.
중첩 객체의 프로퍼티에 접근할 때
function printCatName(user) {
console.log(user.cat.name);
}
const user1 = {
name: 'Captain',
cat: {
name: 'Crew',
breed: 'British Shorthair',
}
}
printCatName(user1); // Crew
만약 존재하지 않는 프로퍼티를 호출하면?
const user2 = {
name: 'Young',
}
console.log(user2.cat); // undefined
printCatName(user2); // TypeError: Cannot read property 'name' of undefined
에러가 발생한다.
따라서 중첩된 객체의 프로퍼티를 다룰때는 user.cat.name에 접근하기 전에
user.cat이 null 또는 undefined가 아니라는것을 검증하고 접근해야 에러를 방지할 수 있다
function printCatName(user) {
console.log(user.cat && user.cat.name);
}
AND연산자로 왼쪽 피연산자가 참일 경우에만 오른쪽 피연산자에 접근한다
이마저도 간결하게 옵셔널 체이닝(?)을 사용
function printCatName(user) {
console.log(user.cat?.name);
}
왼쪽 프로퍼티값이 undefined나 null이 아니라면 그 다음 프로퍼티값을 리턴
그렇지않으면 undefined를 반환
삼항 연산자를 통해 표현하면
function printCatName(user) {
console.log((user.cat === null || user.cat === undefined) ? undefined : user.cat.name);
}
조건 ? true일때 반환 : false일때 반환
null이나 undefined가 아닐때만 user.cat.name 반환
?? : null 병합 연산자
왼편의 값이 null이나 undefined이면 오른편 값 리턴
?. (옵셔널 체이닝 연산자) 가 ?? (널 병합 연산자) 보다 먼저 처리된다
function printCatName(user) {
console.log(user.cat?.name ?? '함께 지내는 고양이가 없습니다.');
}
const user2 = {
name: 'Young',
}
printCatName(user2); // 함께 지내는 고양이가 없습니다.
▼
user.cat?.name : 왼쪽의 user.cat = undefined가 된다
undefined??'함께 지내는 고양이가 없습니다' : 왼쪽값이 undefined이므로 문구를 반환