[JS] ||와 ??의 간단한 차이

toto9602·2024년 6월 14일

얼마 전, <코딩애플>님의 유튜브에서 ??(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일 때, 실제 그 값을 반환!

Nullish 값에서의 동작 (null, undefined)

null

null ?? "value"
// "value"

null || "value"
// "value"

undefined

undefined ?? "value"
// "value" 

undefined || "value"
// "value" 

다른 Falsy 값에서의 동작

NaN

NaN ?? "value"
// NaN

NaN || "value"
// "value"

0

0 ?? "value"
//  0

0 || "value"
// "value"

"" (empty string)

"" ?? "value"
// ""

"" || "value"
// "value" 

(짧은) 결론

  • ?? 연산자는 nullundefined 에 대해서만 우측 피연산자를 반환
  • || 연산자는 nullundefined를 포함하여, 이외 Falsy 값들에 대해서도 우측 피연산자를 연산!
profile
주니어 백엔드 개발자입니다! 조용한 시간에 읽고 쓰는 것을 좋아합니다 :)

0개의 댓글