NULL合体演算子(Nullish coalescing operator) ‘??’の具体例

2021年1月26日JavaScript

NULL合体演算子(Nullish coalescing operator) '??’についてまとめました。

たとえば次のような例をみてみましょう。

NULL合体演算子の具体例

{
//restaurant.numCustomer = 0;
const customers = restaurant.numCustomer || 20;
console.log(customers); 
//もしrestaurant.numCustomer = 0のとき、0ではなく、20を返してしまいます。

const customers = restaurant.numCustomer || 20;
console.log(customers); 
//もしrestaurant.numCustomer = 0のときでも、0を返します。
}

NULL合体演算子はNullishは値、つまりnullとundefinedでなければ継続して評価が続けられます。

0と"空白はfalsyな値ではありますがNullishな値ではないと定義されています。