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

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

オプショナルチェイニングとはJavaScriptやTypeScriptで、オブジェクトのネストされたプロパティに安全にアクセスするための記法です。オプショナルチェイニングを使うと、プロパティがnull または undefinedの場合に、undefinedを返すようになります。

何のために使うのか?

エラーを防止する

例えば、以下のようにUserというオブジェクトが持っていないaddressというプロパティーを参照した場合、TypeError: Cannot read property 'address' of undefinedというエラーが出てしまいます。

const user = {
  name: 'Taro'
};
console.log(user.address.city); // エラーになる!

しかし、オプショナルチェイニングを使うことで、存在しないプロパティにアクセスした場合でもエラーが発生せず、undefinedを返すようになります。

const user = {
  name: 'Taro'
};
console.log(user.address?.city); // undefinedを出力する!

記述量を減らす

オプショナルチェイニングを使わない場合、エラーを回避するためには以下のように全ての値のチェックをする必要が出てきてしまいます。

if (
  user &&
  user.profile &&
  user.profile.contact &&
  user.profile.contact.email
) {
  console.log(user.profile.contact.email);
}

オプショナルチェイニングを使うことで、エラーを回避したい場合でも、以下のようにコードを簡潔に書くことができます。

console.log(user?.profile?.contact?.email);
// 途中で null / undefined があったら、エラーにはならず `undefined` を返す

配列や関数にも使える

配列の場合は、以下のようになります。

const arr = null;
console.log(arr?.[1]); // undefinedを出力する!

関数の場合は、以下のようになります。

const obj = {
  sayHello: null
};
obj.sayHello?.(); // 実行されない、エラーも出ない
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?