MeWrite Docs

SyntaxError: Unexpected token

JavaScriptで構文エラーが発生した場合のエラー

概要

SyntaxError: Unexpected token は、JavaScriptパーサーが予期しない文字やトークンに遭遇した場合に発生するエラーです。

エラーメッセージ

SyntaxError: Unexpected token ')'
SyntaxError: Unexpected token '<'
SyntaxError: Unexpected identifier 'foo'
SyntaxError: Unexpected end of input

原因と解決策

1. カッコの不一致

1
2
3
4
5
6
7
8
9
// NG
function foo( {
  console.log('hello');
}

// OK
function foo() {
  console.log('hello');
}

2. カンマの問題

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// NG: 末尾カンマ(古いブラウザ)
const obj = {
  a: 1,
  b: 2,  // IE11で問題
};

// NG: カンマ忘れ
const arr = [1 2 3];

// OK
const arr = [1, 2, 3];

3. 文字列のクォート

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// NG: クォートの不一致
const str = "hello';

// NG: 改行を含む
const str = "hello
world";

// OK: テンプレートリテラル
const str = `hello
world`;

4. アロー関数

1
2
3
4
5
6
7
8
9
// NG: 複数行で括弧がない
const fn = () =>
  const x = 1;  // SyntaxError

// OK
const fn = () => {
  const x = 1;
  return x;
};

5. JSONパースエラー

1
2
3
4
5
// NG: シングルクォート(JSONは無効)
JSON.parse("{'key': 'value'}");

// OK
JSON.parse('{"key": "value"}');

6. HTMLを読み込んだ場合

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// サーバーがHTMLを返した場合
// SyntaxError: Unexpected token '<'

// デバッグ
fetch('/api/data')
  .then(res => {
    console.log(res.headers.get('content-type'));
    return res.text();  // 一旦テキストで確認
  })
  .then(text => {
    console.log(text);  // HTMLが返ってきていないか確認
  });

7. async/await の間違い

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// NG: awaitがasync関数の外
const data = await fetch('/api');

// OK
async function getData() {
  const data = await fetch('/api');
  return data;
}

// OK: Top-level await(ES2022、モジュールのみ)
// type="module" で読み込まれたスクリプト
const data = await fetch('/api');

8. オプショナルチェーン(古いNode.js)

1
2
3
4
5
// Node.js 14未満ではエラー
const name = user?.profile?.name;

// 互換性のある書き方
const name = user && user.profile && user.profile.name;

デバッグ方法

1
2
3
4
5
// ESLintで構文チェック
// npx eslint your-file.js

// ブラウザのDevToolsでエラー行を確認
// Sources タブでブレークポイントを設定

関連エラー

関連エラー

JavaScript の他のエラー

最終更新: 2025-12-17