반응형

자바스크립트에서 객체를 다룰 때 가장 흔한 에러는 “Cannot read property of undefined” 같은 오류입니다.
이를 해결하기 위해 나온 문법이 Optional Chaining이며,
또한 값이 null이나 undefined일 때만 기본값을 지정하는 Nullish Coalescing이 함께 자주 사용됩니다.
🧩 1. Optional Chaining (?.)
객체 프로퍼티 접근 시 null 또는 undefined가 나오면 에러 대신 undefined를 반환
const user = {
profile: {
name: "홍길동"
}
};
console.log(user.profile?.name); // "홍길동"
console.log(user.address?.city); // undefined (에러 아님!)
📌 기존 방식 (에러 방지):
console.log(user && user.address && user.address.city);
👉 ?. 덕분에 코드가 훨씬 깔끔해짐
🧩 2. Nullish Coalescing (??)
값이 null 또는 undefined일 때만 기본값 사용
let username = null;
let displayName = username ?? "Guest";
console.log(displayName); // "Guest"
📌 기존 || (OR 연산자)와 차이점:
let count = 0;
console.log(count || 10); // 10 (원하지 않는 결과)
console.log(count ?? 10); // 0 (올바른 결과)
👉 ||는 falsy 값(0, "", false)까지 걸러버림
👉 ??는 오직 null과 undefined만 처리
🧩 3. 함께 쓰기
const user = {
profile: { name: null }
};
const name = user.profile?.name ?? "Guest";
console.log(name); // "Guest"
📌 ?.로 안전하게 접근 → ??로 기본값 보장
📊 4. 실무 활용 예시
- API 응답 객체 접근
const city = response.data?.user?.address?.city ?? "Unknown";
- 설정 값 기본값 지정
const limit = config.limit ?? 10;
- React props 안전 처리
function User({ user }) {
return <div>{user?.name ?? "이름 없음"}</div>;
}
⚡ 5. 브라우저 & 환경 지원
- 대부분의 최신 브라우저 지원
- Node.js 14 이상에서 기본 지원
- 구형 브라우저 지원 필요 시 Babel 트랜스파일링 필요
📝 마무리 정리
- ?. → 안전하게 객체 접근 (에러 방지)
- ?? → null/undefined일 때만 기본값 사용
- 함께 쓰면 API 처리, React props 등에서 매우 강력
👉 이제 &&와 ||로 억지 체크할 필요 없습니다.
반응형
'JavaScript, jQuery' 카테고리의 다른 글
| TypeScript 기초 ✅ 타입 시스템과 JavaScript 차이점 (0) | 2025.10.28 |
|---|---|
| jQuery ✅ 자주 쓰는 메소드와 Vanilla JS vs jQuery 비교 (0) | 2025.10.18 |
| 이벤트 위임 ✅ 성능 최적화와 실무 활용법 (0) | 2025.10.17 |
| 이벤트 위임(Event Delegation) – 성능 좋은 이벤트 처리 패턴 (0) | 2025.09.26 |
| Promise와 async/await – 비동기 처리 쉽게 이해하기 (0) | 2025.09.21 |