프로퍼티 접근 에러

라용·2022년 12월 7일
0

자바스크립트 완벽 가이드 책 내용 일부를 발췌 정리한 내용입니다.

존재하지 않는 프로퍼티를 검색하는 것은 에러가 아니라 undefined 입니다. book 이라는 객체는 있으나 subtitle 이라는 프로퍼티가 없다면, book.subtitle 은 undefined 를 반환합니다. 하지만 존재하지 않는 객체에 접근해서 프로퍼티를 검색하면 에러를 반환합니다. book.subtitle.length 는 TypeError 입니다.

book.subtitle; // undefined

let len = book.subtitle.length; // TypeError

프로퍼티 접근 표현식은 점 연산자 왼쪽이 null 이나 undefined 이면 실패합니다. book.author.surname 같은 표현식을 만든다면 book 과 book.author 가 실제로 정의됐는지 확인하는 게 좋습니다.

// 장황하지만 명시적인 방법

let surname = undefined;
if (book) {
    if (book.author) {
        surname = book.author.surname;
    }
}

// surname, null, undefined 중 하나를 가져오는 간결하고 관용적인 방법

surname = book && book.author && book.author.surname;

조건부 프로퍼티 접근 연산자 ?. 을 사용할 수도 있습니다.

let surname = book?.author?.surname;
profile
Today I Learned

0개의 댓글