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?

【React初心者メモ】ヌリッシュ合体演算子(??)

Last updated at Posted at 2025-06-07

ヌリッシュ合体演算子とは

ヌリッシュ合体演算子とは、左の値が null または undefined の場合だけ、右の値を返す演算子です。それ以外(例えば空文字 "" や 0、false などの「falsy」だけど null や undefined じゃない場合)は、左の値をそのまま返します。

具体例

// name は "名無し"
const name = null ?? "名無し";  
// age は 0 (0はnullでもundefinedでもないのでそのまま)
const age = 0 ?? 20;
// text は "" (空文字もそのまま)
const text = "" ?? "空文字";    

何のために使われるのか?

値が存在しない(nullかundefined)場合だけデフォルト値を使いたいときに便利です。
||(論理和)と似ていますが、|| は falsy 全般(0 や "" や false も含む)に反応してしまうため、意図しない動きをすることがあります。

||との比較例

const age1 = 0 || 20;          // 20 が返る(0は falsy)
const age2 = 0 ?? 20;          // 0 が返る(0は null/undefined ではない)

const name1 = "" || "名無し";    // "名無し" が返る(""は falsy)
const name2 = "" ?? "名無し";    // "" が返る(""は null/undefined じゃない)
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?