얼마 전, <코딩애플>님의 유튜브에서 ??(Nullish Coalescing) 연산자와 ?. (Optional Chaining) 연산자를 다루는 영상을 보았었습니다!
+) 해당 영상의 댓글에서 ??와 || 연산자의 차이를 간단히 언급해 주셨는데, 평소 둘의 기능을 크게 구분했던 것 같지 않아 간단히 정리해 보고자 합니다! (_ _)
코딩 애플 강의 영상 (+ 댓글)
MDN Docs : Logical OR
MDN Docs : Nullish_coalescing
[ MDN 설명 ]
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
→ 좌변 피연산자가 null이나 undefined이면 오른쪽 피연산자를, 그렇지 않으면 왼쪽 피연산자를 반환하는 연산자!
The logical OR (||) (logical disjunction) operator for a set of operands is true if and only if one or more of its operands is true.
...
However, the || operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.
→ 하나 이상의 피연산자가 true일 때, 실제 그 값을 반환!
null ?? "value"
// "value"
null || "value"
// "value"
undefined ?? "value"
// "value"
undefined || "value"
// "value"
NaN ?? "value"
// NaN
NaN || "value"
// "value"
0 ?? "value"
// 0
0 || "value"
// "value"
"" ?? "value"
// ""
"" || "value"
// "value"
null 과 undefined 에 대해서만 우측 피연산자를 반환null과 undefined를 포함하여, 이외 Falsy 값들에 대해서도 우측 피연산자를 연산!