MeWrite Docs

ReferenceError: variable is not defined

未定義の変数にアクセスした場合に発生するエラー

概要

ReferenceError: variable is not defined は、存在しない変数にアクセスしようとした場合に発生するエラーです。変数のスコープ、スペルミス、宣言忘れなどが原因です。

エラーメッセージ

Uncaught ReferenceError: myVariable is not defined
    at script.js:5:13
ReferenceError: Cannot access 'x' before initialization

原因

  1. 変数の未宣言: 変数が宣言されていない
  2. スペルミス: 変数名の綴りが間違っている
  3. スコープの問題: 変数が別のスコープで定義されている
  4. TDZ(Temporal Dead Zone): let/const の初期化前アクセス
  5. モジュールのインポート忘れ: 必要なモジュールをインポートしていない

解決策

1. 変数を宣言する

1
2
3
4
5
6
// ❌ 未宣言の変数
console.log(myVariable);

// ✅ 変数を宣言
const myVariable = "Hello";
console.log(myVariable);

2. スペルミスを修正

1
2
3
4
5
6
7
const userName = "Alice";

// ❌ スペルミス
console.log(username);  // ReferenceError

// ✅ 正しいスペル
console.log(userName);

3. スコープを理解する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// ❌ ブロックスコープの問題
if (true) {
    const message = "Hello";
}
console.log(message);  // ReferenceError

// ✅ スコープ外で宣言
let message;
if (true) {
    message = "Hello";
}
console.log(message);

// ✅ または関数から返す
function getMessage() {
    return "Hello";
}
console.log(getMessage());

4. TDZ を回避

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// ❌ 初期化前にアクセス
console.log(x);  // ReferenceError
const x = 5;

// ✅ 宣言後にアクセス
const x = 5;
console.log(x);

// var は巻き上げられる(ただし undefined)
console.log(y);  // undefined(エラーではない)
var y = 5;

5. 関数内の変数スコープ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// ❌ 関数内の変数に外部からアクセス
function greet() {
    const greeting = "Hello";
}
console.log(greeting);  // ReferenceError

// ✅ 変数を返す
function greet() {
    const greeting = "Hello";
    return greeting;
}
console.log(greet());

6. グローバル変数の確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// ブラウザ環境
// ❌ グローバルオブジェクトが未定義
console.log(myGlobal);

// ✅ window オブジェクトで確認
if (typeof window !== "undefined" && window.myGlobal) {
    console.log(window.myGlobal);
}

// ✅ typeof で安全にチェック
if (typeof myGlobal !== "undefined") {
    console.log(myGlobal);
}

7. モジュールのインポート

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// ❌ インポート忘れ
const result = lodash.map([1, 2, 3], n => n * 2);

// ✅ インポートを追加
import _ from 'lodash';
const result = _.map([1, 2, 3], n => n * 2);

// または
import { map } from 'lodash';
const result = map([1, 2, 3], n => n * 2);

8. コールバック内のスコープ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// ❌ this のスコープ問題
const obj = {
    name: "Alice",
    greet: function() {
        setTimeout(function() {
            console.log(this.name);  // undefined または エラー
        }, 100);
    }
};

// ✅ アロー関数を使用
const obj = {
    name: "Alice",
    greet: function() {
        setTimeout(() => {
            console.log(this.name);  // "Alice"
        }, 100);
    }
};

// ✅ bind を使用
const obj = {
    name: "Alice",
    greet: function() {
        setTimeout(function() {
            console.log(this.name);
        }.bind(this), 100);
    }
};

9. async/await でのエラー

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// ❌ await の外で変数を使用
async function fetchData() {
    const response = await fetch('/api/data');
    data = await response.json();  // data が未宣言
}

// ✅ 変数を宣言
async function fetchData() {
    const response = await fetch('/api/data');
    const data = await response.json();
    return data;
}

デバッグのコツ

typeof でチェック

1
2
3
4
// エラーを起こさずにチェック
if (typeof myVariable !== "undefined") {
    // 変数が存在する
}

try-catch でキャッチ

1
2
3
4
5
6
7
try {
    console.log(unknownVariable);
} catch (e) {
    if (e instanceof ReferenceError) {
        console.log("Variable is not defined");
    }
}

デバッガーを使用

1
2
debugger;  // ブレークポイント
console.log(someVariable);

JavaScript の他のエラー

最終更新: 2025-12-08