Skip to main content

How to Resolve "SyntaxError: Unexpected token" Error in JavaScript

The SyntaxError: Unexpected token is one of the most common and generic syntax errors in JavaScript. It's the parser's way of saying, "I found something in your code that I did not expect at this location." While the message can seem vague, the "unexpected token" itself is usually a very strong clue.

This guide will break down the two main categories of this error: general JavaScript syntax mistakes and the specific, very common JSON parsing error Unexpected token '<'.

The Core Problem: A Violation of JavaScript's Syntax Rules

At its heart, this error means you've written something that breaks the grammatical rules of the JavaScript language. The parser was expecting a certain character (like a comma, a parenthesis, or an operator) but found something else instead.

Category 1: General Syntax Errors (Unexpected token '}', ')', etc.)

This category covers simple typos and structural mistakes in your code. The unexpected token is usually a piece of punctuation.

These are some of the most common mistakes:

  • An extra closing brace:
    function myFunc() {
    return true;
    }} // ⛔️ SyntaxError: Unexpected token '}'
  • A missing comma in an object or array:
    let myObj = {
    prop1: 'value1'
    prop2: 'value2' // ⛔️ SyntaxError: Unexpected token ':' (or 'prop2' depending on engine)
    };
  • An unclosed string literal:
    let myString = 'Hello World; // ⛔️ SyntaxError: Unterminated string constant

How to Debug General Syntax Errors

This is a SyntaxError, which means your tools can find it for you before the code even runs.

  1. Check the Console: The error message in your browser's developer console or your terminal will give you the exact filename and line number where the parser got confused.
  2. Use a Code Editor/Linter: Modern code editors (like VS Code) with a linter (like ESLint) are your best defense. They will highlight syntax errors with a red squiggly line as you type, often telling you exactly what is wrong.

Category 2 (Very Common): Unexpected token '<', "<!DOCTYPE "... is not valid JSON

This is a specific and very frequent version of the error that deserves its own section. It happens when you are trying to parse data as JSON, but what you actually received was HTML.

Cause: Trying to Parse HTML as JSON

This error almost always occurs in the context of an API call using fetch() or a similar library.

  • Your front-end code makes a request to an API endpoint (e.g., https://api.example.com/api/user).
  • You expect to receive a JSON response (e.g., {"id": 1, "name": "Alice"}).
  • However, something went wrong on the server, and instead of JSON, the server sent back an HTML error page (like a "404 Not Found" or "500 Internal Server Error" page).
  • Your code then tries to parse this HTML document with JSON.parse() (or response.json()). The very first character of an HTML document is almost always <, which is not a valid start to a JSON string. The parser immediately fails.

Example of problem:

async function fetchData() {
try {
// Imagine 'https://api.example.com/api/non-existent-endpoint' returns a 404 HTML page.
let response = await fetch('https://api.example.com/api/non-existent-endpoint');

// ⛔️ This line will throw the error.
// `response.json()` tries to parse the HTML body as JSON.
let data = await response.json();
} catch (error) {
// The error will be "SyntaxError: Unexpected token '<'..."
console.error('Failed to parse JSON:', error);
}
}

Solution: Check Your API Request

The solution is not to fix your JavaScript parsing, but to fix the API request or the server response.

  1. Check the URL: Is the URL you are fetching correct? A typo is the most common cause of a 404 error.
  2. Check the Network Tab: Open your browser's developer tools and look at the Network tab. Find the failed request, click on it, and inspect the Response tab. You will see the HTML that was returned instead of the JSON you expected. This will often tell you the exact nature of the server error (404, 500, etc.).
  3. Check the Server: If the URL is correct, the problem is on the server. It is either crashing and returning a generic HTML error page, or it's misconfigured and sending a Content-Type header of text/html instead of application/json.
  4. Add Response Validation: Robust client-side code should always check if the response was successful before trying to parse it as JSON.
    let response = await fetch('https://api.example.com/api/data');
    if (!response.ok) {
    // If the status is 4xx or 5xx, don't try to parse it as JSON.
    throw new Error(`HTTP error! status: ${response.status}`);
    }
    let data = await response.json(); // Only call .json() on a successful response.

Conclusion

The SyntaxError: Unexpected token is a broad error with two main categories.

  • If the token is a piece of punctuation like } or ,, the problem is a simple typo in your JavaScript code. Use your code editor's linter and the console's line number to find and fix it.
  • If the token is < and the error mentions JSON, the problem is that you are receiving HTML from an API call instead of JSON. The solution is to debug the network request and the server's response, not the JSON parsing code.