ES2020で新しく提案された機能を試していたところ、??に出くわしました。「ヌル合体演算子」としても知られる演算子。
説明が曖昧で、論理OR演算子とどう違うのかまだわかりません(||
)
説明は非常に簡単です。次の状況があると仮定しましょう。オブジェクトに存在する場合は値を取得し、未定義またはnullの場合は他の値を使用します。
const obj = { a: 0 };
const a = obj.a || 10; // gives us 10
// if we will use ?? operator situation will be different
const obj = { a: 0 };
const a = obj.a ?? 10; // gives us 0
// you can achieve this using this way
const obj = { a: 0 };
const a = obj.a === undefined ? 10 : obj.a; // gives us 0
// it also work in case of null
const obj = { a: 0, b: null };
const b = obj.b ?? 10; // gives us 10
基本的に、この演算子は次に行います。
// I assume that we have value and different_value variables
const a = (value === null || value === undefined) ? different_value : value;
これについての詳細は、MDNWebドキュメントにあります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加