21
13

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の ||・?? の違い、Rubyの ||を解説

Posted at

truthy / falsy とは?

JavaScript(や Ruby などの動的型付け言語)では、値を論理的に評価(Boolean評価)したときに true になるか false になるかによって、以下のように分類されます。

  • truthy(トゥルーシー):Booleanで評価すると true になる値
  • falsy(フォールシー):Booleanで評価すると false になる値

これは if (...) {} や ||, ??, ! などの評価でよく使われます。

JSの || と ?? の違いまとめ(全 falsy 値パターン付き)

console.log("false || 'default' =>", false || "default");     // "default"
console.log("false ?? 'default' =>", false ?? "default");     // false

// 0
console.log("0 || 'default' =>", 0 || "default");             // "default"
console.log("0 ?? 'default' =>", 0 ?? "default");             // 0

// 空文字 ""
console.log('"" || "default" =>', "" || "default");           // "default"
console.log('"" ?? "default" =>', "" ?? "default");           // ""

// null
console.log("null || 'default' =>", null || "default");       // "default"
console.log("null ?? 'default' =>", null ?? "default");       // "default"

// undefined
console.log("undefined || 'default' =>", undefined || "default"); // "default"
console.log("undefined ?? 'default' =>", undefined ?? "default"); // "default"

// NaN
console.log("NaN || 'default' =>", NaN || "default");         // "default"
console.log("NaN ?? 'default' =>", NaN ?? "default");         // NaN

JavaScript の falsy 値一覧:

  • false
  • 0
  • ""(空文字)
  • null
  • undefined
  • NaN

JSの ?? は、左辺が null または undefined のときに右側を返す という演算子。
false や 0 を「ちゃんと値として扱いたい」ときに使えるのが ??

Rubyの || の基本挙動

Ruby では ||左側が「偽(false または nil)」なら右側を使う という挙動です。

puts nil || "default"    # => "default"
puts false || "default"  # => "default"
puts "" || "default"     # => "" (空文字は truthy)
puts 0 || "default"      # => 0 (0 も truthy)

Ruby では false と nil 以外は truthy(真) とみなされるらしいです。

Rubyで || を複数並べた場合

Ruby では a || b || c のように複数書いたとき、最初に truthy な値が返される。

puts nil || false || "value"     # => "value"
puts false || nil || 0           # => 0
puts nil || "first" || "second"  # => "first"

Rubyで ?? 的なことをやるには?

Ruby には ?? はありませんが、nil? を使えば似たことができます。

def null_coalesce(val, default)
  val.nil? ? default : val
end

puts null_coalesce(nil, "default")   # => "default"
puts null_coalesce(false, "default") # => false
puts null_coalesce(0, "default")     # => 0

終わりに

株式会社シンシアでは、実務未経験のエンジニアの方や学生エンジニアインターンを採用し一緒に働いています。
※ シンシアにおける働き方の様子はこちら

弊社には年間100人程度の実務未経験の方に応募いただき、技術面接を実施しております。
この記事が少しでも学びになったという方は、ぜひ wantedly のストーリーもご覧いただけるととても嬉しいです!

21
13
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
21
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?