LoginSignup
0
0

null合体演算子について理解する

Posted at

目次

  1. 背景
  2. null合体演算子(??)とは
  3. ユースケース

1. 背景

null合体演算子(??)を片手に収まる回数しか使ったことがない為です。

2. null合体演算子(??)とは

  • 論理演算子の一種です。

  • 左辺が null または undefined の場合に右の値を返し、それ以外の場合に左の値を返します。

    const foo = null ?? 'default string';
    console.log(foo);
    // Expected output: "default string"
    
    const baz = 0 ?? 42;
    console.log(baz);
    // Expected output: 0
    

論理OR演算子 (||)と似てますが、こちらはfalsyな値の場合に右の値を返し、それ以外の場合に左の値を返します。

3. ユースケース

undefied,null以外のfalsyな値も有効な値として解釈したい時です。
例えば0 や ''、falseです。

参考

参考になる記事を書いて下さった皆様に感謝致します!

0
0
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
0
0