JavaScript - Optional Chaining

Hunter Joe·2024년 8월 21일
post-thumbnail

옵셔널 체이닝 이란?

옵셔널 체이닝(.?)은 존재하지 않을 수 있는 객체 프로퍼티 또는 메서드를 안전하게 호출하는 문법

// syntax
object?.property
  • ?.은 객체의 깊은 속성 값을 안전하게 접근할 수 있도록 도와준다.
  • 중첩 객체에서 존재하지 않는 속성에서 접근해도 명시적 런타임 에러가 아닌 undefined를 반환한다.

NOTE
프로퍼티가 없는 중첩 객체를 에러 없이 안전하게 접근할 수 있다.
.?앞의 평가 대상이 undifinednull이면 평가를 멈추고 undefined를 반환한다.

Example (Without optional chaining)

const food = {
  breakfast: {
    meal: 'apple',
    desert: {
      drink: 'juice',
    },
  },
  lunch: {
    drink: 'coffee',
    meal: 'pasta',
  },
};

console.log(food.lunch.desert.drink);
// Cannot read properties of undefined (reading 'drink')

위 코드의 동작 순서를 살펴보자

  1. food.lunch → 존재하므로 통과
  2. food.lunch.desert→ 존재 ❌,food.lunch.desert = undefined
  3. undefined.drinkundifined에는 drink 프로퍼티가 없으므로 에러 발생

JS는 존재하지 않는 desert프로퍼티에서 drink를 읽으려고 하는 시점에 에러를 일으킨다.
Cannot read properties of undefined (reading 'drink')

Example (With optional chaining)

const food = {
  breakfast: {
    meal: 'apple',
    desert: {
      drink: 'juice',
    },
  },
  lunch: {
    drink: 'coffee',
    meal: 'pasta',
  },
};

console.log(food.lunch.desert?.drink ?? "No drink found");
// Cannot read properties of undefined (reading 'drink')
  1. food.lunch.desertundifined 이므로 ?.이후의 평가는 중단된다.
  2. No drink found가 반환됨 → 명시적 런타임 에러가 아닌 설정된 기본 값 불러오기 가능
profile
Improvise, Adapt, Overcome

0개의 댓글