본문 바로가기
이것저것 공부

옵셔널 체이닝(Optional Chaining)

by 성동구불주먹 2025. 3. 5.

옵셔널 체이닝이란

옵셔널 체이닝(optional chaining) 연산자(?.)는 객체가 null 또는 undefined일 때 발생하는 오류를 방지하는 연산자이다.

객체의 특정 속성에 안전하게 접근할 수 있다.

 


 

 

옵셔널 체이닝 예제

[예제] 옵셔널 체이닝이 없을 때

const user = null;
console.log(user.name); // ❌ TypeError: Cannot read properties of null (reading 'name')

 

[예제] 옵셔널 체이닝이 있을 때

const user = null;
console.log(user?.name); // ✅ undefined (에러 발생 X)

 

[예제] 깊은 객체에서 안전한 접근

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

console.log(user?.profile?.name); // ✅ "Alice"
console.log(user?.address?.city); // ✅ undefined (에러 X)

 

위의 예제처럼 ?.을 사용하면 중첩된 객체에서도 안전하게 값에 접근이 가능하다.

 


 

 

옵셔널 체이닝의 단점

 

1. 잘못된 데이터 구조를 파악하기 어려움

[예제] user?.address?.city를 사용할 경우, address가 없다는 걸 바로 알기 어렵고 그냥 undefine로 처리됨

 

2. 가독성이 떨어짐

 

3. 옵셔널 체이닝을 사용하면, 어디에서 정확히 null이 발생하는지 파악하기 어려움

 

4. 쓰기에는 사용할 수 없다.

let user = {};
user?.name = "Alice"; // ❌ SyntaxError: Invalid left-hand side in assignment

 

 


결론

- 객체가 null 또는 undefined일 수 있을 때만 사용

- 남용하지않고, 데이터 구조가 올바른지 확인 필요

- 읽기는 가능하지만, 쓰기에는 사용 불가

반응형