
&&, OR ||)와 옵셔널 체이닝(?.)의 차이점둘 다 안전하게 데이터에 접근하거나 조건부 로직을 처리할 때 사용되지만, 역할과 사용법이 다르다는 게 핵심.
&&, OR ||)&&) - 앞의 값이 true일 때만 뒤의 값 반환const user = { name: "Alice" };
console.log(user && user.name); // ✅ "Alice"
user가 존재하면 user.name을 반환 user가 null이나 undefined라면 오류 없이 null 반환const user = null;
console.log(user && user.profile.name); // ❌ TypeError 발생!
user가 null이기 때문에 user.profile에 접근하면 오류 발생 ||) - 앞의 값이 false면 뒤의 값 반환 (기본값 설정할 때 사용)const name = "" || "Default Name"; // ✅ "Default Name"
"")은 falsy 값이므로 "Default Name" 반환 null, undefined, 0, false, NaN, "" 같은 falsy 값이 앞에 있으면 뒤의 값으로 대체됨 ?.)const user = { profile: { name: "Alice" } };
console.log(user?.profile?.name); // ✅ "Alice"
user와 user.profile이 존재할 경우에만 name에 접근 null이나 undefined가 있어도 오류 없이 undefined 반환const user = null;
console.log(user.profile.name); // ❌ TypeError: Cannot read properties of null
user가 null이면 profile에 접근하려고 할 때 에러 발생 ?.)을 사용하면 이 문제를 방지할 수 있음 console.log(user?.profile?.name); // ✅ undefined (에러 없이 처리됨)
| 🚀 기능 | ✅ **논리 연산자 (&&, ` | |
|---|---|---|
| 목적 | 조건부 렌더링, 기본값 설정 | 안전한 객체/배열 접근 |
| 사용 상황 | 값이 존재하는지 확인하고 다음 로직 실행 | 중첩된 객체 속성을 안전하게 탐색할 때 |
| 에러 발생 여부 | 중간 값이 null이면 오류 발생 가능 | null이나 undefined일 경우에도 에러 발생 안 함 |
| 문법 | user && user.name | user?.name |
| 기본값 설정 가능 여부 | OR(` |
const isLoggedIn = true;
return (
<div>
{isLoggedIn && <p>Welcome, User!</p>} // ✅ 로그인 상태일 때만 표시
</div>
);
isLoggedIn이 true일 때만 <p> 태그가 렌더링됨 const user = null;
console.log(user?.profile?.name); // ✅ undefined (에러 없이 처리)
user가 null이어도 에러 발생 없이 undefined 반환 | 상황 | 추천 문법 |
|---|---|
| 조건부 렌더링 | ✅ && 사용 (e.g., isLoggedIn && <Component />) |
| 기본값 설정 | ✅ ` |
| 깊은 객체 접근 (안전성 중요) | ✅ ?.(옵셔널 체이닝) 사용 |
| 불확실한 API 데이터 처리 | ✅ ?.로 안전한 접근 |
&& / || → 조건부 렌더링이나 기본값 설정에 유용 ?.) → 깊은 객체 접근 시 에러 없이 안전하게 사용 가능 💡 ➡ 조건부 렌더링은 &&, 안전한 데이터 접근은 ?.로 처리하면 깔끔하고 안전한 코드가 완성됨