home강의 홈으로
Section 11. 문제들에 대비하기
Lesson 4. 옵셔널 체이닝

유효하지 않을 수 있는 참조에 의한 문제들

🌐 네트워크 요청 등, 어떤 값이 들어올지 모르는 상황에서

⚠️ 에러가 발생하는 상황들

// undefined로부터 값에 접근할 때 let undefObj; console.log(undefObj.x); // null부터 값에 접근할 때 let nullObj = null; console.log(nullObj.x); // 무효한 배열에 접근할 때 let undefArry; console.log(undefArry[1]); // 존재하지 않는 함수를 호출할 때 let noFunc = {} noFunc.func();

다음과 같은 상황에서 에러를 피하려면?

  • 결과에 prop3이 있다면 가져와야 하는 상황
// 최소 undefined // 최대 {prop1:{prop2:{prop3:'성공!'}}} // 까지 반환하는 함수 const rand = () => Math.random() < 0.75; const notSure = () => rand() ? { prop1: rand() ? { prop2: rand() ? { prop3: rand() ? '성공!' : undefined } : undefined } : undefined } : undefined; console.log(JSON.stringify(notSure()));


const result = notSure(); console.log(JSON.stringify(result)); // ⚠️ 바로 접근하려 할 시에는 실패시 에러 console.log(result.prop1.prop2.prop3);


// 방법 1 const result = notSure(); if (result) { if (result.prop1) { if (result.prop1.prop2) { console.log(result.prop1.prop2.prop3); } } } // 방법 2 const result = notSure(); console.log( result && result.prop1 && result.prop1.prop2 && result.prop1.prop2.prop3 ); // 방법 3 const result = notSure(); try { console.log(result.prop1.prop2.prop3); } catch { console.log(undefined); }



?. - 옵셔널 체이닝 optional chaining 연산자

  • 호출 대상이 undefinednull이어도 오류를 발생시키지 않음 - 대신 undefined 반환
  • 있을지 없을지 모르는 것으로부터 값을 읽거나 실행할 때 사용
  • 👉 MDN 문서 보기
let undef = undefined; console.log( undef?.x, undef?.['x'], undef?.[1], {}.func?.() );


// 옵셔널 체이닝을 사용한 방법 const result = notSure(); console.log( result?.prop1?.prop2?.prop3 );

💡 유무가 불확실한 함수를 호출할 때도 유용

const objs = [ { func () { console.log(1) } }, {}, { func () { console.log(2) } }, {}, { func () { console.log(3) } }, ] objs.forEach(o => o.func?.());

🤔얄코에게 질문하기질문은 반.드.시 이리로 보내주세요! ( 강의사이트 질문기능 ✖ )

강의에서 이해가 안 되거나 실습상 문제가 있는 부분,
설명이 잘못되었거나 미흡한 부분을 메일로 알려주세요!

답변드린 뒤 필요할 경우 본 페이지에
관련 내용을 추가/수정하도록 하겠습니다.

이메일 주소
yalco@yalco.kr
메일 제목 (반드시 아래 제목을 붙여넣어주세요!)
[질문] 제대로 파는 자바스크립트 (유료 파트) 11-4

🛑질문 전 필독!!

  • 구글링을 먼저 해 주세요. 들어오는 질문의 절반 이상은 구글에 검색해 보면 1분 이내로 답을 찾을 수 있는 내용들입니다.
  • 오류 메시지가 있을 경우 이를 구글에 복붙해서 검색해보면 대부분 짧은 시간 내 해결방법을 찾을 수 있습니다.
  • 강의 페이지에 추가사항 등 놓친 부분이 없는지 확인해주세요. 자주 들어오는 질문은 페이지에 추가사항으로 업데이트됩니다.
  • "유료파트의 강의페이지는 어디 있나요?" - 각 영상의 시작부분 검은 화면마다 해당 챕터의 강의페이지 링크가 있습니다.
  • 질문을 보내주실 때는 문제가 어떻게 발생했고 어떤 상황인지 등을 구체적으로 적어주세요. 스크린샷을 첨부해주시면 더욱 좋습니다.
🌏 Why not change the world?