
ワタル
今日は、javascriptのNull 合体演算子の話だよ。 英語だと、Nullish coalescing operatorね。

アキラ
これピンポイントで検索するしかたどり着けない内容だろ。 しかもgoogleって記号の検索弱いから
javascript "??"
ってやってもまともに検索できないしな。
ワタル
うう、そうかも。まぁ気を取り直して始めるよ。
const a = x ?? y
って書いたときに、xがnullかundefinedのときaがyになって、それ以外のときはaがxになるやつね。

アキラ
便利。これ使わないと大体
const a = (x !== null) && (x !== undefined) ? x : y
とか
const a = (x === null) || (x === undefined) ? y : x
になってめんどい。

ワタル
その条件文でもいいんだけど、前者は否定のANDなので一見だとわかりにくいし、後者は後者でxとyがチェンジしててそれはそれでわかりにくいよ。だから
x ?? y
できるようになったときは嬉しかったね。

アキラ
でもさ
const a = x || y
でも大体同じじゃない。

ワタル
それだとFalsy(偽値)判定だから、xが0とか""のときも、aがyになっちゃう。こういうの使いたいときってxがまともじゃなかったらyって書きたいときだから、0が正しい値としてくる可能性があるときは使えないんだよね。 挙動をまとめると
> 3 ?? "後ろ"
3
> 0 ?? "後ろ"
0
> "" ?? "後ろ"
""
> null ?? "後ろ"
"後ろ"
> undefined ?? "後ろ"
"後ろ"
> 3 || "後ろ"
3
> 0 || "後ろ"
"後ろ"
> "" || "後ろ"
"後ろ"
> null || "後ろ"
"後ろ"
> undefined || "後ろ"
"後ろ"

アキラ
はーい。

ワタル
ところで条件判定で、Nullishだったらって書きたいときどうすればいいと思う?

アキラ
えっ。さっき書いた
||
か&&
でくっつけた微妙に長い条件だよね。
ワタル
そうなんだけど
const a = (x != null) ? x : y
とか
const a = (x == null) ? y : x
でもいいのよ

アキラ
そんなんでいいの?
undefined
来たらどうなるの?よくわからないんだけど...
ワタル
=
は3つじゃなくて2つなのがポイントだよ!じゃ
x == null
とx != null
の挙動を見てみようか。> 0 == null
false
> "" == null
false
> null == null
true
> undefined == null
true
> 0 != null
true
> "" != null
true
> null != null
false
> undefined != null
false

アキラ
ほんとだ! Nullish判定(nullかundefined)できてる。

ワタル
ちなみに
x == undefined
でも同じね。
> 0 == undefined
false
> "" == undefined
false
> null == undefined
true
> undefined == undefined
true

アキラ
うひょー!まじか。
11.9.3 The Abstract Equality Comparison Algorithm
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
中略
2. If x is null and y is undefined, return true.
3. If x is undefined and y is null, return true.
https://262.ecma-international.org/5.1/#sec-11.9.3より

ワタル
だから
if (x == null) {
なんてif文で、undefinedがきてもtrueになるのよ。