Optional Chaining 연산자(?.)는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다.
?. 연산자는 참조가 nullish(null 또는 undefined)일 때, 에러 발생 대신 undefined 리턴한다.
참조가 누락될 가능성이 있는 경우에 사용하면
더짧고 간단한 표현식으로 연결된 속성에 접근 가능하며
null 값에 대한 에러 발생을 방지할 수 있다.
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
optional chaining 연산자는 참조나 기능이 undefined 또는 null일 수 있을 때 연결된 객체의 값에 접근하는 단순화할 수 있는 방법을 제공한다.
<script>
// 옵션 체이닝 사용 X
let nestedProp = obj.first && obj.first.second;
// 옵션 체이닝 사용 O
let nestedProp = obj.first?.second;
// 옵션 체이닝을 사용한 위의 코드는 아래와 같이 해석
let nestedProp = ((obj.first === null || obj.first === undefined) ? undefined : obj.first.second);
</script>
존재하지 않을 수 있는 메서드를 호출할 때, optional chaining을 사용할 수 있다.
함수 호출에 optional chaining을 사용하면 메서드를 찾을 수 없는 경우,
예외를 발생시키는 것 대신 undefined를 반환한다.
<script>
let result = someInterface.customMethod?.();
</script>
someInterface?.customMethod?.()
callbacks 또는 fetch 메서드를 사용한다면,
그 존재 여부를 테스트하여 함수를 호출해야 하는 경우가 있다.
이때 ?.을 사용하면 다음 예시와 같이 추가 테스트를 피할 수 있다.
<script>
// Written as of ES2019
function doSomething(onContent, onError) {
try {
// ... do something with the data
}
catch (err) {
if (onError) { // Testing if onError really exists
onError(err.message);
}
}
}
// Using optional chaining with function calls
function doSomething(onContent, onError) {
try {
// ... do something with the data
}
catch (err) {
onError?.(err.message); // no exception if onError is undefined
}
}
</script>
optional chaining 연산자를 사용하여 속성에 표현식으로 접근할 때 대괄호 표기법(the bracket notation of the property accessor)을 사용할 수 있다.
<script>
let nestedProp = obj?.['prop' + 'Name'];
</script>
<script>
let object = {};
object?.property = 1; ❌
// Uncaught SyntaxError: Invalid left-hand side in assignment
</script>
<script>
let arrayItem = arr?.[42];
</script>
중첩된 구조에서는 optional chaining을 여러 번 사용할 수 있다.
<script>
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?.();
</script>
null 병합 연산자는 optional chaining를 사용한 후에 아무 값도 찾을 수 없을 때 기본 값을 주기 위해 사용될 수 있다.
<script>
let customer = {
name: "Carl",
details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city
</script>
null 병합 연산자란?
왼쪽 피연산자가 null 또는 undefined일 때 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자
참조 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Optional_chaining