본문 바로가기

JavaScript/Modern JavaScript

[JavaScript] 옵셔널 체이닝 (Optional Chaining)

객체를 활용하여 데이터를 표현하다보면, 이런식으로 중첩된 객체를 작성하는 일이 빈번하다.

function printCatName(user) {
  console.log(user.cat.name);
}

const user1 = {
  name: 'Captain',
  cat: {
    name: 'Crew',
    breed: 'British Shorthair',
  }
}

printCatName(user1); // Crew

 

중첩된 개체를 작성할 때, 주의할 부분이 있음.

onst user2 = {
  name: 'Young',
}

console.log(user2.cat); // undefined
printCatName(user2); // TypeError: Cannot read property 'name' of undefined

데이터를 다루다보면 우리가 예상한 프로퍼티를 가지고 있지 않은 경우가 있다.

cat 프로퍼티를 가지고 있지 않은 user2 는, cat 프로퍼티가 undefined 이기 때문에 user2.cat.name 에 접근하려는 순간 에러가 발생함.

 

따라서, printCatName과 같이 중첩된 객체의 프로퍼티를 다룰 때에는, 그 값에 접근하기 전에 user.cat 값이 null 이나 undefined 라는 것부터 확인해야한다.

 

function printCatName(user) {
  console.log(user.cat && user.cat.name);
}

이처럼 if 문을 활용할 수도 있으나, 더욱 간결하게 작성할 수 있는 방법이 있다.

 

 

옵셔널 체이닝(Optional Chaining)

function printCatName(user) {
  console.log(user.cat?.name);
}

물음표와 마침표를 붙여서 사용하는 것이 옵셔널 체이닝 연산자이다. 옵셔널 체이닝 연산자의 왼편 프로퍼티 값이 undefined 나 null 이 아니라면 그 다음 프로퍼티 값을 리턴하고, 그렇지 않은 경우에는 undefined 값을 리턴한다.

 

function printCatName(user) {
  console.log((user.cat === null || user.cat === undefined) ? undefined : user.cat.name);
}

동작 원리는 이처럼 나타낼 수 있다.

 

다음과 같이 null 병합 연산자와 사용할 수도 있다.

function printCatName(user) {
  console.log(user.cat?.name ?? '함께 지내는 고양이가 없습니다.');
}

const user2 = {
  name: 'Young',
}

printCatName(user2); // 함께 지내는 고양이가 없습니다.