0
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?

JavaScriptにおける三項演算子(?:)と Null合体演算子(??)の違い

Posted at

はじめに

最初、a ? a : ba ?? b は同じ意味だと思っていました。

でも実際は違いました。

この記事では、「nullish」値と「falsy」値の判定の違いについて解説します。
また、どの値が nullish か、どの値が falsy かを一覧できる表や、実際に試せるコードも紹介します。
自分用のチートシートとしても役立てられる内容になっています。

三項演算子(?:)と Null合体演算子(??)の違い

Nullish(??)

??null または undefined だけを特別扱いします。

x = a ?? b

このとき、anull または undefined でなければ x = a になります。

例:

  • a = ''(空文字)の場合 → x = ''

Falsy(?:)

?:(三項演算子)は falsy かどうかを判定します。

x = a ? a : b

このとき、a が falsy なら x = b になります。

例:

  • a = '' の場合 → x = b

結論

  • x = a ?? banullish かどうかを判定する
  • x = a ? a : bafalsy かどうかを判定する

チートシート

Nullish と Falsy 演算子の判定表

よく使う演算子の中で、nullish を判定できるのは ?? だけです。
それ以外(?:, ||, if(), !x など)はすべて falsy 判定になります。

# 演算子・構文 判定種類
1 ?? nullish
2 ? falsy
3 || falsy
4 boolean() falsy
5 if() falsy
6 !!x falsy
7 !x falsy

Nullish vs Falsy 判定表

# aの値 aの型 a ?? "default" a ? a : "default" IsNullish IsFalsy
1 null object default default true true
2 undefined undefined default default true true
3 empty string '' string default false true
4 'hello' string hello hello false false
5 0 number 0 default false true
6 -1 number -1 -1 false false
7 NaN number NaN default false true
8 false boolean false default false true
9 [] object [] [] false false
10 {} object {} {} false false

実際に試すコード

const testValues = [
  { label: "null", value: null },
  { label: "undefined", value: undefined },
  { label: "empty string ''", value: "" },
  { label: "'hello'", value: "hello" },
  { label: "0", value: 0 },
  { label: "-1", value: -1 },
  { label: "NaN", value: NaN },
  { label: "false", value: false },
  { label: "[]", value: [] },
  { label: "{}", value: {} },
];

const results = testValues.map(({ label, value }) => ({
  'value of a' : label,
  'type of a': typeof value,
  'a ?? "default"': value ?? "default",           // shows result of ??
  'a ? a : "default"': value ? value : "default", // shows result of ?:
  IsNullish: value == null,                       // true only for null/undefined
  IsFalsy: !value                                 // true for falsy values
}));

console.table(results);

参考リンク

0
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
0
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?