SW Engineer & Developer/React Craft

옵셔널 체이닝(Optional Chaining)

ByteCraft 2025. 2. 1. 15:36

옵셔널 체이닝(Optional Chaining) 개요

옵셔널 체이닝(Optional Chaining, ?.)은 객체 프로퍼티가 존재하지 않을 경우 오류 없이 안전하게 접근할 수 있도록 도와주는 문법입니다.

✅ 주요 특징

  • 객체 프로퍼티가 null 또는 undefined일 경우 즉시 undefined 반환
  • 긴 체이닝에서도 안전하게 접근 가능
  • 불필요한 if 문이나 && 연산자를 줄여 코드 가독성 향상

1️⃣ 기본 문법

const user = {
  profile: {
    name: "Alice",
  },
};

console.log(user.profile?.name); // "Alice"
console.log(user.profile?.age);  // undefined (존재하지 않는 프로퍼티)
console.log(user.account?.email); // undefined (존재하지 않는 객체)
  • user.profile?.name → profile이 존재하므로 정상 접근
  • user.profile?.age → profile에는 age가 없으므로 undefined 반환
  • user.account?.email → account가 없으므로 undefined 반환 (오류 없음)

2️⃣ 함수 호출에서의 옵셔널 체이닝

const obj = {
  getName: () => "Alice",
};

console.log(obj.getName?.()); // "Alice"
console.log(obj.getAge?.());  // undefined (오류 발생X)
  • ?.()를 사용하면 존재하지 않는 함수 호출을 방지할 수 있음

3️⃣ 배열 요소 접근

const users = [{ name: "Alice" }];
console.log(users[0]?.name); // "Alice"
console.log(users[1]?.name); // undefined (오류 없음)
  • 배열 요소가 존재하지 않더라도 안전하게 접근 가능

4️⃣ 옵셔널 체이닝 없이 접근하는 경우

console.log(user.account.email); 
// TypeError: Cannot read properties of undefined (reading 'email')
  • user.account가 undefined인 경우, email을 읽으려 하면 오류 발생
  • 옵셔널 체이닝을 사용하면 이를 방지할 수 있음

5️⃣ 옵셔널 체이닝과 nullish coalescing(??) 함께 사용

console.log(user.account?.email ?? "이메일 없음");
// "이메일 없음" (account가 없으므로 undefined → 기본값 설정)
  • ?. 연산자로 undefined 방지
  • ?? 연산자로 기본값 설정 가능

✅ 결론

옵셔널 체이닝(?.)을 사용하면 객체 프로퍼티, 함수, 배열 요소 등에 안전하게 접근할 수 있습니다. 이를 활용하면 불필요한 if 문을 줄이고 코드의 안정성과 가독성을 높일 수 있습니다. 🚀