5.

Uncaught TypeError: Cannot read properties of null (reading

編集
この記事の要点
  • Uncaught TypeError: Cannot read properties of null (reading 'xxx')null のプロパティにアクセスしたエラー
  • 原因 ①: document.getElementById で要素が見つからない (typo / 順序)
  • 原因 ②: API レスポンスの値が null なのに展開した
  • 対処 ①: optional chaining obj?.prop
  • 対処 ②: 事前 null チェック if (obj) { obj.prop }

 

エラーの状況

Uncaught TypeError: Cannot read properties of null (reading 'value')
    at script.js:5

# Chrome / Firefox 共通
# 旧バージョン: "Cannot read property 'value' of null"
# 新バージョン: "Cannot read properties of null (reading 'value')"

null.xxx のように null オブジェクトのプロパティを読み取ろうとした時のエラー。最も頻発する JavaScript エラーの一つ。

原因と対処

原因 1: DOM 要素が見つからない

// HTML


// JavaScript
const input = document.getElementById("user_name");  // ← typo
const value = input.value;  // → Cannot read properties of null

// 修正 1: ID を正確に
const input = document.getElementById("username");

// 修正 2: null チェック
const input = document.getElementById("username");
if (input) {
    const value = input.value;
}

// 修正 3: optional chaining (ES2020+)
const value = document.getElementById("username")?.value;

原因 2: スクリプトが DOM 読み込み前に実行



    


    




    
    




    




    

原因 3: API レスポンスが null

// API 取得
const response = await fetch("/api/user/123");
const user = await response.json();
// user が null の場合
console.log(user.name);  // → Cannot read properties of null

// 修正 1: optional chaining
console.log(user?.name);  // → undefined (エラーなし)

// 修正 2: null 合体演算子
const name = user?.name ?? "ゲスト";

// 修正 3: 早期 return
if (!user) {
    console.log("ユーザーが見つかりません");
    return;
}
console.log(user.name);

原因 4: 配列メソッドの戻り値が null や undefined

// find は見つからないと undefined
const users = [{id: 1}, {id: 2}];
const user = users.find(u => u.id === 999);
console.log(user.name);  // → Cannot read properties of undefined

// 修正
const user = users.find(u => u.id === 999);
console.log(user?.name ?? "見つかりません");

// querySelector も同じ
const el = document.querySelector(".not-exist");
el.style.color = "red";  // ← null エラー

// 修正
const el = document.querySelector(".not-exist");
if (el) el.style.color = "red";

原因 5: 正規表現の match() が null

// マッチしない場合 null
const m = "abc".match(/\d+/);
console.log(m[0]);  // → Cannot read properties of null

// 修正
const m = "abc".match(/\d+/);
console.log(m?.[0] ?? "数値なし");

// match の戻り値
"abc123".match(/\d+/);    // → ["123", index: 3, ...]
"abc".match(/\d+/);        // → null

原因 6: localStorage / sessionStorage が null

// 未設定のキー
const data = localStorage.getItem("user");  // → null
const obj = JSON.parse(data);
console.log(obj.name);  // → Cannot read properties of null

// 修正
const data = localStorage.getItem("user");
if (data) {
    const obj = JSON.parse(data);
    console.log(obj.name);
}

// 短縮
const obj = JSON.parse(localStorage.getItem("user") || "{}");
console.log(obj.name ?? "未登録");

Optional Chaining と Nullish Coalescing

// ?. (Optional Chaining) - ES2020+
const value = obj?.prop;              // obj が null/undefined → undefined
const nested = obj?.a?.b?.c;          // 連鎖
const method = obj?.method?.();       // メソッド呼び出し
const item = arr?.[0];                // 配列アクセス
const dynamic = obj?.[propName];      // 動的キー

// ?? (Nullish Coalescing) - ES2020+
const name = user?.name ?? "ゲスト";
// user?.name が null or undefined のみデフォルト
// 0 や "" は採用される (|| との違い)

const count = data?.count ?? 0;
// data が null → 0
// data.count が 0 → 0 (採用)
// data.count が undefined → 0

// 比較
data?.count || 0;     // count が 0 だと 0 採用ではなくフォールバックされる
data?.count ?? 0;     // count が 0 なら 0 採用

デバッグの流れ

  1. エラー行を特定: スタックトレースの 1 行目
  2. 該当オブジェクトの値を確認: console.log(obj)
  3. null の場合: なぜ null か? (DOM 未生成 / API 失敗 / 引数なし)
  4. 修正: 上記の対処方法から選択
  5. 類似箇所を予防的に修正: 同じパターンが他にもないか

類似エラー

エラー意味
Cannot read properties of nullこのページ
Cannot read properties of undefinedundefined のプロパティ (同じ対処)
obj is not a function関数として呼ぼうとした
obj is not iterablefor..of や spread で配列以外
Cannot set properties of nullnull に代入
obj.length is undefined配列だと思ったオブジェクト

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. Uncaught TypeError: Illegal invocation
  2. Form submission canceled because the form is not connected
  3. Uncaught TypeError: location.href is not a function
  4. Access to XMLHttpRequest at 'url1' from origin 'url2' has been blocked
  5. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')