Skip to main content

옵셔널 체이닝(optional chaining)


1. 개요

Optional chaining은 객체의 프로퍼티나 메서드가 존재하지 않을 수도 있을 때, 안전하게 접근할 수 있도록 해주는 문법이다. 주로 JavaScript에서 사용되며, ?. 연산자를 사용한다.

Optional chaining의 가장 큰 장점 중 하나는 NullPointerException(자바) 또는 TypeError: Cannot read property of null(JS) 같은 런타임 오류를 피할 수 있다.

즉, Optional chaining은 객체의 중첩 속성이나 메서드가 null 또는 undefined일 수 있을 때, 안전하게 접근할 수 있도록 도와주며, 이로 인해 NullPointerException과 같은 런타임 오류를 방지하고 코드 가독성을 높이는 데 유리하다.

단, JavaScript의 optional chaining은 set 에는 사용할 수 없다.


2. 기본 문법

obj?.prop
obj?.[expr]
obj?.method?.()

예제 1: 객체 프로퍼티 접근

const user = {
  name: 'Alice',
  address: {
    city: 'Seoul'
  }
};

console.log(user.address?.city);    // "Seoul"
console.log(user.contact?.email);   // undefined (오류 발생 안 함!)

예제 2: 배열 요소 접근

const users = null;
console.log(users?.[0]);  // undefined

예제 3: 함수/메서드 호출

const user = {
  sayHi() {
    return "Hello!";
  }
};

console.log(user.sayHi?.());     // "Hello!"
console.log(user.sayBye?.());    // undefined (sayBye가 없어서 안전하게 undefined 반환)

3. 주의사항

  • undefinednull이 아닌 다른 falsy 값(0, false, '')에 대해서는 작동하지 않는다.
  • 왼쪽 값이 null 또는 undefined일 때만 undefined를 반환하고, 그렇지 않으면 그 뒤의 속성이나 메서드에 접근을 시도한다.
  • optional chaining은 읽기 전용이라서 대입은 할 수 없다.
let user = null;
// user?.name = "Bob"; // ❌ SyntaxError

4. 장점

4.1 NullPointerException 방지

  • 체인의 중간 값이 null 또는 undefined여도 오류 없이 안전하게 처리된다.
user.address.city     // ❌ TypeError 발생 가능
user?.address?.city   // ✅ 안전하게 undefined 반환

4.2 코드 가독성 향상

  • 여러 번의 null 체크를 줄여서 코드가 짧고 명확해진다.
// Before
if (user && user.address && user.address.city) {
  console.log(user.address.city);
}

// After
console.log(user?.address?.city);

4.3 함수 호출

user?.sayHi?.();  // 메서드가 없으면 아무 일도 안 일어남

4.4 배열/객체 접근

const name = users?.[0]?.name;  // users가 null이어도 에러 안 남