1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

論理演算子「??」「||」

Posted at

??(null合体演算子)

左側の値が null または undefined の場合に右側の値を返す。

sample1
let a = null;

// 以下は同じ結果になる
let b = (a !== null && a !== undefined) ? a : "デフォルト値";

let b = a ?? "デフォルト値";

??=(null合体代入演算子)

左側の変数が null または undefined の場合にのみ代入する。

sample2
let a = null;

// 以下は同じ結果になる
if (a === null || a === undefined) {
  a = "新しい値";
}

a ??= "新しい値";

||(OR演算子)

左側の値が「falsy」な場合に右側の値を返す。

sample3
let a = 0;

// 以下は同じ結果になる
let b = a ? a : "デフォルト値";

let b = a || "デフォルト値";

||=(OR代入演算子)

左側の値がfalsyの場合にのみ代入する。

sample4
let a = 0;

// 以下は同じ結果になる
if (!a) {
  a = 10;
}

a ||= 10;

「??」「||」の使い分け

  • 0 や "" を許容する場合は ?? を使う
  • 0 や "" を許容しない場合は || を使う
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?