LoginSignup
2
2

【JavaScript】??と||の違い

Last updated at Posted at 2023-11-18

??

??は左辺がnullundefinedである場合に右の値を返し、それ以外の場合は左の値を返します。

const foo = null ?? 'default'
console.log(foo) // 'default'

const baz = 0 ?? 1
console.log(baz) // 0

||

||は左辺の値がnullundefinedの場合に加えて、何らかの偽値であった場合に右の値を返します。

const foo = null || 'default'
console.log(foo) // 'default'

const baz = 0 || 1
console.log(baz) // 1

偽値には以下のようなものがあります。

説明
null null 値が存在しないことを示します。
undefined undefined プリミティブ値。
false 論理値型 false。
NaN 数値型 数値ではない。
0 数値型 ゼロ (従って、 0.00x0 なども含みます)。
-0 数値型 マイナスゼロ(従って、 -0.0-0x0 等も含みます)。
0n 長整数型 長整数型のゼロ(従って、 0x0n も含みます)。なお、長整数型にはマイナスゼロはありません。 0n の負の数は 0n です。
"" 文字列型 空文字列。''`` も含みます。
document.all オブジェクト JavaScript で唯一の偽値のオブジェクトは、組み込みの document.all です。
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2