
웹 개발에서 중첩된 객체 구조를 다루는 일은 매우 흔하다. 특히 API 응답을 처리할 때, 데이터의 안전한 접근은 매우 중요한 과제다.
먼저 일반적인 객체 접근 방식을 살펴보자
const response = {
data: {
userList: [
{
name: 'kim',
info: {
tel: '010-1234-5678',
email: 'kim@gmail.com'
}
}
]
}
}
function getUserEmailByIndex(userIndex) {
return response.data.userList[userIndex].info.email;
}
이 코드의 문제점은?
function getUserEmailByIndex(userIndex) {
if (response.data.userList) {
return response.data.userList[userIndex].info.email;
}
return '알 수 없는 에러가 발생했습니다';
}
이 방법도 완벽하지 않다.
data가 없다면?userList[userIndex]가 없다면?info가 없다면?function getUserEmailByIndex(userIndex) {
const email = response?.data?.userList?.[userIndex]?.info?.email;
return email ?? '알 수 없는 에러가 발생했습니다';
}
function getUserEmailByIndex(userIndex) {
return response?.data?.userList?.[userIndex]?.info?.email ?? '이메일 정보 없음';
}
// 실제 사용 예시
const email1 = getUserEmailByIndex(0); // 'kim@gmail.com'
const email2 = getUserEmailByIndex(999); // '이메일 정보 없음'
// 복잡한 객체 구조에서도 안전하게 접근
const deepValue = obj?.prop1?.prop2?.[0]?.prop3 ?? 'default';
// 메서드 호출도 안전하게
const result = obj.method?.() ?? 'method not found';
// 배열 메서드와 함께 사용
const firstItem = array?.filter(x => x.active)?.[0] ?? 'no active items';
null이나 undefined일 때만 대체 값을 사용''(빈 문자열), 0, false 값은 유효한 값으로 처리||)와의 차이// OR 연산자는 falsy 값을 모두 대체
const value1 = 0 || '대체값'; // '대체값'
const value2 = '' || '대체값'; // '대체값'
// 널 병합 연산자는 null과 undefined만 대체
const value3 = 0 ?? '대체값'; // 0
const value4 = '' ?? '대체값'; // ''
옵셔널 체이닝은 현대 자바스크립트에서 없어서는 안 될 중요한 기능이 되었다. 특히 API 응답처럼 불확실한 데이터 구조를 다룰 때 코드의 안정성과 가독성을 크게 향상시켜준다. 널 병합 연산자와 함께 사용하면 더욱 강력한 도구가 된다.