From 4d50bcf05516c7c368266acb25a39dd6802d0464 Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Fri, 18 Feb 2022 10:28:13 +0900 Subject: 2022/02/04 時点の英語版に同期 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../operators/nullish_coalescing_operator/index.md | 178 ++++++++++----------- 1 file changed, 86 insertions(+), 92 deletions(-) (limited to 'files/ja/web/javascript/reference') diff --git a/files/ja/web/javascript/reference/operators/nullish_coalescing_operator/index.md b/files/ja/web/javascript/reference/operators/nullish_coalescing_operator/index.md index 20eaf23925..3d74a548ce 100644 --- a/files/ja/web/javascript/reference/operators/nullish_coalescing_operator/index.md +++ b/files/ja/web/javascript/reference/operators/nullish_coalescing_operator/index.md @@ -1,147 +1,141 @@ --- -title: Null 合体 (??) +title: Null 合体演算子 (??) slug: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator tags: - JavaScript - - Language feature - - Operator - - Reference + - 言語機能 + - 演算子 + - リファレンス - nullish coalescing +browser-compat: javascript.operators.nullish_coalescing translation_of: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator --- -

{{JSSidebar("Operators")}}

+{{JSSidebar("Operators")}} -

Null 合体演算子 (??) は論理演算子の一種です。この演算子は左辺が {{jsxref("null")}} または {{jsxref("undefined")}} の場合に右の値を返し、それ以外の場合に左の値を返します。

+**Null 合体演算子 (`??`)** は論理演算子の一種です。この演算子は左辺が {{jsxref("null")}} または {{jsxref("undefined")}} の場合に右の値を返し、それ以外の場合に左の値を返します。 -

OR 演算子 (||) と違い、nullundefined 以外の falsy な値のときには左の値を返します。つまり、左辺が ''0 の場合は左の値を評価して返します。その他の例については以下を参照してください。

+これは[論理 OR 演算子 (`||`)](/ja/docs/Web/JavaScript/Reference/Operators/Logical_OR) の特殊形と見なすことができます。そちらは左辺の値が `null` や `undefined` だけでなく、何らかの{{Glossary("falsy", "偽値")}}であった場合に右辺値を返すものです。つまり、 `||` を使って別の変数 `foo` に何らかの既定値を与える場合、一部の偽値(例えば `''` や `0`)を使用可能とみなすと、予想外の動作に遭遇することがあります。詳しい例は以下を参照してください。 -
{{EmbedInteractiveExample("pages/js/expressions-nullishcoalescingoperator.html")}}
+Null 合体演算子は[演算子の優先順位](/ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)が下から 5 番目で、 `||` のすぐ下、[条件(三項)演算子](/ja/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)のすぐ上とします。 - +{{EmbedInteractiveExample("pages/js/expressions-nullishcoalescingoperator.html")}} -

構文

+## 構文 -
leftExpr ?? rightExpr
-
+```js +leftExpr ?? rightExpr +``` -

説明

+## 例 -

Null 合体演算子は左辺が {{jsxref("null")}} または {{jsxref("undefined")}} の場合に右辺の値を返します。

+### Null 合体演算子の使用 -

変数にデフォルト値を代入する

+次の例では、既定値を設定していますが、`null` や `undefined` 以外の値は保持されます。 -

以前は、変数にデフォルト値を代入したい場合、一般的なパターンは OR 演算子 (||) を使用することでした:

+```js +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); // "" (空文字列は null でも undefined でもないため) +console.log(valC); // 42 +``` + +### 変数に既定値を代入する -
let foo;
+以前は、変数に既定値を代入したい場合の一般的なパターンは、論理 OR 演算子([`||`](/ja/docs/Web/JavaScript/Reference/Operators/Logical_OR))を使用することでした。
 
-//  foo is never assigned any value so it is still undefined
-let someDummyText = foo || 'Hello!';
+```js +let foo; -

しかし、|| が論理演算子であるため、左辺の値は評価によって強制的にブール値になり、falsy な値 (0, '', NaN, null, undefined) が返されることはありません。この動作は、0'', NaN を有効な値と考えている場合、予期せぬ結果を引き起こす可能性があります。

+// foo には何も値が代入されていないので、 undefined のままです +let someDummyText = foo || 'Hello!'; +``` -
let count = 0;
+しかし、`||` が論理演算子であるため、左辺の値は評価によって強制的に論理値になり、偽値(`0`, `''`, `NaN`, `null`, `undefined`)が返されることはありません。この動作は、 `0` や `''`, `NaN` を有効な値と考えている場合、予期せぬ結果を引き起こす可能性があります。
+
+```js
+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 ""
-
+console.log(qty); // 42 であり 0 ではない +console.log(message); // "hi!" であり "" ではない +``` -

Null 合体演算子は、左辺の値が null もしくは undefined のどちらか (その他の falsy な値は含みません) に評価された場合にのみ右辺の値を返すことで、この潜在的な危険を回避します:

+Null 合体演算子は、左辺の値が `null` もしくは `undefined` のどちらか(その他の falsy な値は含みません)に評価された場合にのみ右辺の値を返すことで、この潜在的な危険を回避します。 -
let myText = ''; // An empty string (which is also a falsy value)
+```js
+let myText = ''; // 空文字列(偽値)
 
 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)
-
+console.log(preservingFalsy); // '' (myText は undefined でも null でもない) +``` -

短絡評価

+### 短絡評価 -

OR 演算子や AND 演算子と同様に、左辺が null でも undefined でもないことが証明された場合、右辺の式は評価されません。

+OR 演算子や AND 演算子と同様に、左辺が `null` でも `undefined` でもないことが判明した場合、右辺の式は評価されません。 -
function A() { console.log('A was called'); return undefined;}
+```js
+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
+// "A was called"、 "C was called" のあと "foo" と出力
+// A() は undefined を返すため、両方の式が評価されるため
 
 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
-
+// "B was called" のあと "false" と出力 +// B() は false を返すため(そして null も undefined も返さない)、 +// 右辺の式は評価されない +``` -

AND 演算子、OR 演算子とつなげて使わない

+### AND 演算子、OR 演算子とつなげて使わない -

AND 演算子 (&&) と OR 演算子 (||) を直接 ?? とつなげて使うことはできません。このような場合 SyntaxError が発生します。

+AND 演算子 (`&&`) と OR 演算子 (`||`) を直接 `??` と組み合わせて使うことはできません。このような場合 [`SyntaxError`](/ja/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) が発生します。 -
null || undefined ?? "foo"; // raises a SyntaxError
-true || undefined ?? "foo"; // raises a SyntaxError
+```js example-bad +null || undefined ?? "foo"; // SyntaxError が発生 +true || undefined ?? "foo"; // SyntaxError が発生 +``` -

ただし、カッコを付けて明示的に優先順位を示すのは正しいやり方です。

+ただし、カッコを付けて明示的に優先順位を示すのは正しいやり方です。 -
(null || undefined) ?? "foo"; // returns "foo"
-
+```js example-good +(null || undefined) ?? "foo"; // "foo" を返す +``` -

オプショナルチェイニング演算子 (?.) との関係

+### オプション連鎖演算子 (`?.`) との関係 -

Null 合体演算子は、nullundefined を特定の値として扱いますが、オプショナルチェイニング演算子 (?.) も同様の扱いをします。この演算子は、null または undefined である可能性のあるオブジェクトのプロパティにアクセスするのに便利です。

+Null 合体演算子は、 `undefined` と `null` を特定の値として扱いますが、[オプション連鎖演算子 (`?.`)](/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining) も同様の扱いをします。この演算子は、`null` または `undefined` である可能性のあるオブジェクトのプロパティにアクセスするのに便利です。 -
let foo = { someFooProp: "hi" };
+```js
+let foo = { someFooProp: "hi" };
 
-console.log(foo.someFooProp?.toUpperCase());  // "HI"
-console.log(foo.someBarProp?.toUpperCase()); // undefined
-
+console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI" +console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available" +``` -

+## 仕様書 -

次の例では、デフォルト値を設定していますが、nullundefined 以外の値は保持されます。

+{{Specifications}} -
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;
+{{Compat}}
 
-console.log(valA); // "default for A"
-console.log(valB); // "" (as the empty string is not null or undefined)
-console.log(valC); // 42
-
- -

仕様

- - - - - - - - - - - - -
仕様書
-

{{SpecName('ESDraft', '#prod-Nulli', 'nullish coalescing expression')}}

-
- -

ブラウザー実装状況

- -

{{Compat("javascript.operators.nullish_coalescing")}}

- -

関連情報

- - +## 関連情報 + +- [オプション連鎖演算子](/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining) +- [論理 OR (`||`) 演算子](/ja/docs/Web/JavaScript/Reference/Operators/Logical_OR) +- [デフォルト引数](/ja/docs/Web/JavaScript/Reference/Functions/Default_parameters) -- cgit v1.2.3-54-g00ecf