0
0

論理演算子「&&」「||」「??」の違い

Last updated at Posted at 2024-07-24

はじめに

論理演算子の厳密な定義について、こちらの記事でまとめてみようと思います。
説明する内容は下記の通りです。

// 論理積
const x = A && B

// 論理和
const y = A || B

// null合体演算子
const z = A ?? B

論理積「&&」

const x = A && B

定義

A x 定義
true B Aがtrue(真値)の場合、Bの判定結果に委ねる
false A Aがfalse(偽値)の場合、Aの値が返却される

論理値がfalseになる例

  • 0
  • 空文字列
  • false
  • null
  • undefined
// 定義に基づいた出力例
const x1 = 1 && 2 // A:true, B:true → 2が返却
const x2 = 0 && 2 // A:false, B:true → 0が返却
const x3 = 2 && 0 // A:true, B:false → 0が返却

// falseが混じる出力例
const x4 = "" && "string" // A:false, B:true → ""が返却
const x5 = false && true // A:false, B:true → falseが返却
const x6 = null && "string" // A:false, B:true → nullが返却
const x7 = undefined && "string" // A:false, B:true → undefinedが返却

論理和「||」

const x = A || B

定義

A x 定義
true A Aがtrue(真値)の場合、Aの値が返却される
false B Aがfalse(偽値)の場合、Bの判定結果に委ねる

論理値がfalseになる例

  • 0
  • 空文字列
  • false
  • null
  • undefined
// 定義に基づいた出力例
const x1 = 1 || 2 // A:true, B:true → 1が返却
const x2 = 0 || 2 // A:false, B:true → 2が返却
const x3 = null || 0 // A:false, B:false → 0が返却

// falseが混じる出力例
const x4 = "" || "string" // A:false, B:true → stringが返却
const x5 = false || true // A:false, B:true → trueが返却
const x6 = null || "string" // A:false, B:true → stringが返却
const x7 = undefined || "string" // A:false, B:true → stringが返却

null合体演算子「??」

const x = A ?? B

定義

A x 定義
true A Aがtrue(真値)の場合、Aの値が返却される
false B Aがfalse(偽値)の場合、Bの判定結果に委ねる

論理値がfalseになる例

  • null
  • undefined
// 定義に基づいた出力例
const x1 = 1 ?? 2 // A:true, B:true → 1が返却
const x2 = null ?? 2 // A:false, B:true → 2が返却
const x3 = null ?? undefined // A:false, B:false → undefinedが返却

// falseが混じる出力例
const x4 = null ?? "string" // A:false, B:true → stringが返却
const x5 = undefined ?? "string" // A:false, B:true → stringが返却

最後に

上記より、論理積「&&」と論理和「||」の違いについて、定義が異なっていてfalseになる条件が同じになります。その一方で、論理和「||」とnull合体演算子「??」の違いについては、定義が同じでfalseになる条件が異なります。

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