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?

# オプショナルチェイニングとは?nullやundefinedでも安全に書く方法

0
Posted at

JavaScriptを書いていると、こんなエラーに遭遇したことはありませんか?

Cannot read properties of undefined

これは null や undefined に対してプロパティやメソッドにアクセスした ときに起きるエラーです。

この記事では、そんな問題をスマートに解決できる
オプショナルチェイニング について解説します。


よくあるエラー例

ユーザー情報を表示したい場合

const user = null;

console.log(user.name);

理由
usernull または undefined なのに、そのプロパティ(name)を直接読み込もうとしているからです。

従来の回避方法

if 文でチェックする

if (user && user.name) {
  console.log(user.name);
}

問題点

  • ネストが深くなりがち
  • 書くのが面倒
  • 可読性が下がる

オプショナルチェイニングとは?

オプショナルチェイニング(? は、
対象が null または undefined の場合でも、
エラーを出さずに undefined を返してくれる構文 です。

基本的な使い方

プロパティアクセス

const user = null;

console.log(user?.name);
// => undefined(エラーにならない)
  • usernull / undefinedundefined
  • 値があれば そのまま取得

ネストが深いオブジェクトでも安全

const user = {
  profile: {
    name: "Taro",
  },
};

console.log(user?.profile?.name);
// => "Taro"

メソッド呼び出しにも使える

const user = {
  greet() {
    return "こんにちは";
  },
};

console.log(user.greet?.());
// => "こんにちは"

メソッドが存在しない場合

const user = {};

console.log(user.greet?.());
// => undefined

配列アクセスでも使える

const users = null;

console.log(users?.[0]?.name);
// => undefined
  • 配列がない
  • 要素がない

どちらでも 安全 です。


よくある利用シーン

APIレスポンスの処理

const data = response?.data?.user?.name;

APIの返却内容が不安定な場合にとても便利です。

オプショナルチェイニングの注意点

値が「ない」ことを隠してしまう

user?.name;
  • エラーは出ない
  • でも 本来必要な値が無いことに気づきにくい

👉 本当に null を許容していいかは設計次第


null合体演算子(??)と一緒に使う

デフォルト値を設定したい場合

const name = user?.name ?? "ゲスト";
  • null / undefined"ゲスト"
  • 空文字 ""0そのまま使われる

|| との違い

const name = user?.name || "ゲスト";

👉 空文字 "" の場合も "ゲスト" になる

const name = user?.name ?? "ゲスト";

👉 null / undefined のみ "ゲスト"

まとめ

  • オプショナルチェイニング(?)は安全アクセスの構文
  • null / undefined でも エラーにならない
  • ネストが深いオブジェクト で特に効果的
  • ?? と組み合わせるとさらに便利
  • 使いすぎには注意

おわりに

オプショナルチェイニングを使うと、
「エラー回避のための if 文」から解放 されます。

ただし、
「本当に値が無くていいのか?」 を意識しながら使うのが、 重要 です 🚀

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?