MeWrite Docs

TypeError: Cannot read properties of undefined

undefinedに対してプロパティアクセスを試みた場合に発生するJavaScriptの一般的なエラー

概要

TypeError: Cannot read properties of undefinedは、undefinedの値に対してプロパティ(.name[0]など)を読み取ろうとしたときに発生するJavaScriptの一般的なエラーです。変数の初期化忘れ、非同期処理の完了前のアクセス、APIレスポンスの想定外の形式など、さまざまな原因で発生します。

エラーメッセージ

TypeError: Cannot read properties of undefined (reading 'propertyName')  (Chrome / Node.js)
TypeError: variable is undefined  (Firefox)
TypeError: undefined is not an object (evaluating 'variable.propertyName')  (Safari)

原因

このエラーは以下の原因で発生します:

  1. 変数の初期化忘れ: 変数を宣言したが値を代入していない
  2. オブジェクトが存在しない: 存在すると思っているオブジェクトが実際にはundefined
  3. 配列の範囲外アクセス: 存在しないインデックスの要素にアクセス
  4. 関数の戻り値がない: return文がない関数の結果を使用
  5. 非同期処理の完了前にアクセス: APIデータ取得前に変数を参照
  6. 深いネストでの中間オブジェクトが未定義: data.user.profile.nameで途中がundefined

解決策

1. オプショナルチェイニング(?.)を使用する

最も現代的で安全な方法です。

1
2
3
4
5
6
7
8
9
// NG: undefinedでエラー
let user;
console.log(user.name);

// OK: オプショナルチェイニング
console.log(user?.name); // undefined(エラーなし)

// 深いネストでも安全
console.log(data?.user?.profile?.name);

2. if文で存在チェック

1
2
3
4
5
6
7
8
9
// オブジェクトの存在確認
if (user) {
  console.log(user.name);
}

// より厳密なチェック
if (user !== undefined && user !== null) {
  console.log(user.name);
}

3. デフォルト値を設定(Null合体演算子)

1
2
3
4
5
// Null合体演算子(??)でデフォルト値
const name = user?.name ?? 'ゲスト';

// 環境変数にデフォルト値
const port = process.env.PORT ?? 3000;

4. 配列アクセスの安全化

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const colors = ['red', 'green'];

// NG: 範囲外アクセス
console.log(colors[2].toUpperCase()); // エラー

// OK: オプショナルチェイニング
console.log(colors[2]?.toUpperCase()); // undefined

// OK: 長さチェック
if (colors.length > 2) {
  console.log(colors[2].toUpperCase());
}

5. 関数の戻り値を保証する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// NG: returnがないルートがある
function findUser(id) {
  const users = [{ id: 1, name: 'Alice' }];
  if (users[0].id === id) {
    return users[0];
  }
  // ここでundefinedが返る
}

// OK: 必ず値を返す
function findUserSafe(id) {
  const users = [{ id: 1, name: 'Alice' }];
  return users.find(u => u.id === id) ?? null;
}

環境別の対処法

フレームワーク固有の発生パターンと対処法は、以下の個別記事を参照してください:

よくある間違い

  • awaitのつけ忘れ: async関数内で非同期関数を呼ぶ際にawaitを忘れると、Promiseオブジェクトが返り、そのプロパティにアクセスしてエラー
  • &&による安易なチェック: user && user.nameuserが空文字列""0でも偽になる。undefined/nullだけ避けたいならオプショナルチェイニングを使う
  • 深いネストでの油断: data.user.profile.nameで途中がundefinedの可能性を見逃す

関連エラー

関連エラー

JavaScript の他のエラー

最終更新: 2026-02-03