Null 合体演算子 (??
) は論理演算子の一種です。この演算子は左辺が null
または undefined
の場合に右の値を返し、それ以外の場合に左の値を返します。
OR 演算子 (||
) と違い、null
と undefined
以外の falsy な値のときには左の値を返します。つまり、左辺が ''
や 0
の場合は左の値を評価して返します。その他の例については以下を参照してください。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
See PR #1482 regarding the addition of this example.
構文
leftExpr ?? rightExpr
説明
変数にデフォルト値を代入する
以前は、変数にデフォルト値を代入したい場合、一般的なパターンは OR 演算子 (||
) を使用することでした:
let foo;
// foo is never assigned any value so it is still undefined
let someDummyText = foo || 'Hello!';
しかし、||
が論理演算子であるため、左辺の値は評価によって強制的にブール値になり、falsy な値 (0
, ''
, NaN
, null
, undefined
) が返されることはありません。この動作は、0
や ''
, NaN
を有効な値と考えている場合、予期せぬ結果を引き起こす可能性があります。
let count = 0;
let text = "";
let qty = count || 42;
let message = text || "hi!";
console.log(qty); // 42 and not 0
console.log(message); // "hi!" and not ""
Null 合体演算子は、左辺の値が null
もしくは undefined
のどちらか (その他の falsy な値は含みません) に評価された場合にのみ右辺の値を返すことで、この潜在的な危険を回避します:
let myText = ''; // An empty string (which is also a falsy value)
let notFalsyText = myText || 'Hello world';
console.log(notFalsyText); // Hello world
let preservingFalsy = myText ?? 'Hi neighborhood';
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
短絡評価
OR 演算子や AND 演算子と同様に、左辺が null
でも undefined
でもないことが証明された場合、右辺の式は評価されません。
function A() { console.log('A was called'); return undefined;}
function B() { console.log('B was called'); return false;}
function C() { console.log('C was called'); return "foo";}
console.log( A() ?? C() );
// logs "A was called" then "C was called" and then "foo"
// as A() returned undefined so both expressions are evaluated
console.log( B() ?? C() );
// logs "B was called" then "false"
// as B() returned false (and not null or undefined), the right
// hand side expression was not evaluated
AND 演算子、OR 演算子とつなげて使わない
AND 演算子 (&&
) と OR 演算子 (||
) を直接 ??
とつなげて使うことはできません。このような場合 SyntaxError
が発生します。
null || undefined ?? "foo"; // raises a SyntaxError
true || undefined ?? "foo"; // raises a SyntaxError
ただし、カッコを付けて明示的に優先順位を示すのは正しいやり方です。
(null || undefined) ?? "foo"; // returns "foo"
オプショナルチェイニング演算子 (?.) との関係
Null 合体演算子は、null
と undefined
を特定の値として扱いますが、オプショナルチェイニング演算子 (?.
) も同様の扱いをします。この演算子は、null
または undefined
である可能性のあるオブジェクトのプロパティにアクセスするのに便利です。
let foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase()); // "HI"
console.log(foo.someBarProp?.toUpperCase()); // undefined
例
次の例では、デフォルト値を設定していますが、null
や undefined
以外の値は保持されます。
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;
console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
仕様
ブラウザー実装状況
BCD tables only load in the browser
実装の進捗
この機能はまだブラウザー間相互運用の安定性に達していないため、以下の表はこの機能の日々の実装状況を示しています。このデータは、 JavaScript の標準テストスイートである Test262 で、該当する機能テストを Nightly ビルド、または各ブラウザーの JavaScript エンジンの最新リリースで実行することで生成されます。