상세 컨텐츠

본문 제목

[자바스크립트] 옵셔널 체이닝 예제

카테고리 없음

by esoesmio 2023. 5. 16. 02:03

본문

// 옵셔널 체이닝을 사용한 방법
// 최소 undefined
// 최대 {prop1:{prop2:{prop3:'성공!'}}}
// 까지 반환하는 함수
const rand = () => Math.random() < 0.75;

const notSure = () => rand() ? {
    prop1: rand() ? {
        prop2: rand() ? {
            prop3: rand() ? '성공!' : undefined
        } : undefined
    } : undefined
} : undefined;



// 방법 1
// const result = notSure();
//
// if (result) {
//     if (result.prop1) {
//         if (result.prop1.prop2) {
//             console.log(result.prop1.prop2.prop3);
//         }
//     }
// }



const result = notSure();

console.log(
    result?.prop1?.prop2?.prop3
);

댓글 영역