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の「||」と「? :」の違いをカンタン解説!

Last updated at Posted at 2025-06-21

はじめに

JavaScriptを書いていると、こんなコードに出会うことがあります。

パターン1
const No = this._Param.No || this.No;

一見便利そうなこの書き方。
でも、少し複雑な事情があります。
例えばこんな書き方とも比較されることが多いです。

パターン2
const No = this._Param.No !== undefined ? this._Param.No : this.No;

両方とも「_Param.No があればそれを使って、なければ this.No を使う」と思いがちですが、実は結果が異なるケースがあるんです。

「||」を使った代入:シンプルだけど false や 0 には注意

const No = this._Param.No || this.No;

この書き方では、this._Param.No が true と評価される値(たとえば文字列や正の数など)であればその値を使います。ただし、次のような値は「値がない」とみなされてしまいます

  • false
  • 0
  • ''(空文字)
  • null
  • undefined
    つまり、ちゃんと意味のある値なのに無視されてしまう可能性があるんです。

例:

this._Param.No = 0;
const No = this._Param.No || 100; // No は 100 になってしまう!

「? :」を使った代入:false や 0 もきちんと使える

const No = this._Param.No !== undefined ? this._Param.No : this.No;

この書き方では、「_Param.No が undefined かどうか」だけを判定します。なので、false, 0, '' などの値もしっかり「ある値」として扱われるのがポイント。

例:

this._Param.No = 0;
const No = this._Param.No !== undefined ? this._Param.No : 100; // No は 0 のまま、期待通り!

まとめ:どちらを使うべき?

書き方 特徴 向いているケース
パターン1 シンプルで短い 値が false や 0 でも問題ないとき(ざっくりチェック)
パターン2 より正確な判定ができる 0 や false を無視せずに使いたいとき

最後にひとこと

false や 0 を正しく扱えるようになると、コードのバグも減って安心感がアップします。用途に応じて適切な構文を選んでいきたいですね!

0
0
1

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?