4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

?と??の違いについて利用例を見ながら簡単に解説します

名称と参考

  • ?.
    • オプショナルチェーン演算子

  • ??
    • Null 合体演算子

それぞれの解説

  • ?.
    • 名称
      • オプショナルチェーン
    • どういう時に使うか
      • オブジェクトのプロパティアクセス時に、存在するかどうかわからないものにアクセスその際にエラーを出したくないtという時に使えます
    • なぜ使うか
      • この演算子を利用してアクセスするオブジェクトまたはメソッドが undefined または null の場合、エラーが発生することなく、式が途中で終了し、undefined と評価されます
      • エラーでコード実行を止めたくない場合に使えます
  • ??
    • 名称
      • Null合体演算子
    • どういう時に使うか
      • 左辺が null または undefined の場合に右の値を返し、それ以外の場合に左の値を返します
    • なぜ使うか
      • 左辺がnullかundefinedの可能性がある式やメソッドを利用し、ただ全体としては何かを返す必要がある場合にデフォルト値(若干語弊がありますが)の役割として右辺に値をセットすることができるからです

それぞれの具体的な利用法

  • ?. オプショナルチェーン
const explainObjectChain = {
  animal: (() => "I'm animal")
};

console.log(explainObjectChain.animal?.())
// animalメソッドは存在するので、"I'm animal"が返る

console.log(explainObjectChain.someNonExistentMethod?.());
// null または undefinedが返る
// someNonExistentMethodというメソッドはexplainObjectChainオブジェクトに無いので本来であればエラーになるが?.のおかげでエラーでは出ずにコード全体としては処理が続いてくれる
  • ?? Null合体演算子
const explainNullCoalescingOperator = {
  thisIsNullSoItWillReturnRightSideValue: null;
};

console.log(explainNullCoalescingOperator.thisIsNullSoItWillReturnRightSideValue ?? "I'm right side value, I will returned"
// "I'm right side value, I will returned" という文字列が返される

まとめ

  • そもそも違いの前に持っている機能が違う
  • 字面が似過ぎてややこしいのでちょくちょく見直したい
4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?