개발Story

optional chaining 연산자 (?.) 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다.

 

?. 연산자는 . 체이닝 연산자와 유사하게 작동하지만, 만약 참조가 nullish (en-US) (null 또는 undefined)이라면, 에러가 발생하는 것 대신에 표현식의 리턴 값은 undefined로 단락된다. 함수 호출에서 사용될 때, 만약 주어진 함수가 존재하지 않는다면, undefined를 리턴한다.

 

간단히 말하면 객체에 참조에러를 방지 할 수 있는 문법이다.

 

[문법] : object key값앞에 ?를 붙여주어 error를 방지하면 된다.

 obj?.prop
    obj?.[expr]
    arr?.[index]
    func?.(args)

 

예제 : JavaScript Demo: Expressions - Optional chaining operator

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

 [코드 개선]

// 개선전
let nestedProp = obj.first && obj.first.second;

//개선후
let nestedProp = obj.first?.second;

[중첩사용] :중첩된 구조에서는 optional chaining을 여러 번 사용할 수 있다

let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // detailed address is unknown
  }
};
let customerCity = customer.details?.address?.city;

// … this also works with optional chaining function call
let duration = vacations.trip?.getTime?.();

[null 연산자와 같이 사용] :널 병합 연산자는 optional chaining를 사용한 후에 아무 값도 찾을 수 없을 때 기본 값을 주기 위해 사용될 수 있다.

let customer = {
  name: "Carl",
  details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city

참조 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Optional_chaining

'Javascript > 문법' 카테고리의 다른 글

[javascript] Promise.all()  (0) 2022.11.02
[javascript] 정규표현식  (0) 2022.08.28
[javascript] scroll event(등록, 삭제)  (0) 2022.07.31
[javascript] sort 함수.  (1) 2022.06.07
[Javascript] Slice, Splice, Split  (0) 2022.05.07
profile

개발Story

@슬래기

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!