?? (null 合体) と || (論理 OR) はいつ使用すればよいですか? 質問する

?? (null 合体) と || (論理 OR) はいつ使用すればよいですか? 質問する

関連JavaScript には「null 合体」演算子がありますか?- JavaScript には、??より頻繁に使用される演算子が追加されました。以前は、ほとんどの JavaScript コードで が使用されていました||

let userAge = null

// These values will be the same. 
let age1 = userAge || 21
let age2 = userAge ?? 21

どのような状況で動作が変わるのでしょう??||?

ベストアンサー1

OR演算子は||左辺が偽の一方、null 合体演算子は、 left がまたは の??場合に right の値を使用します。nullundefined

これらの演算子は、最初の値が欠落している場合にデフォルト値を提供するためによく使用されます。

しかし、OR演算子は、||左辺の値に""or0またはfalse(これらは誤った値) :

console.log(12 || "not found") // 12
console.log(0  || "not found") // "not found"

console.log("jane" || "not found") // "jane"
console.log(""     || "not found") // "not found"

console.log(true  || "not found") // true
console.log(false || "not found") // "not found"

console.log(undefined || "not found") // "not found"
console.log(null      || "not found") // "not found"

多くの場合、 left がnullまたは の場合にのみ right の値が必要になりますundefined。そのために null 合体演算子??があります。

console.log(12 ?? "not found") // 12
console.log(0  ?? "not found") // 0

console.log("jane" ?? "not found") // "jane"
console.log(""     ?? "not found") // ""

console.log(true  ?? "not found") // true
console.log(false ?? "not found") // false

console.log(undefined ?? "not found") // "not found"
console.log(null      ?? "not found") // "not found"

演算子??現在のNodeのLTSバージョン(v10 および v12)、TypeScript または Node の一部のバージョンで使用できます。

演算子??が追加されたタイプスクリプト3.72019年11月に遡ります。

そして最近では、??オペレーターはES2020に含まれる、Node 14(2020 年 4 月リリース)でサポートされています。

null 合体演算子??がサポートされている場合、通常は OR 演算子の代わりにそれを使用します||(そうしない正当な理由がない限り)。

おすすめ記事