Skip to content
jshacks.dev
Fundamentals

JavaScript SyntaxError Explained With Causes and Fixes

JavaScript throws SyntaxError when text is not valid code or JSON. See why you cannot catch most of them, how JSON.parse fails, and fixes for common messages.

9 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the JavaScript, Node.js and Vite logos.

Most errors happen while a program runs. A SyntaxError happens before it runs, when the engine reads the source and cannot make sense of it: a missing bracket, a stray comma, a reserved word used as a name. That timing explains the single most confusing fact about it, which is that you usually cannot catch one. A try block around a line with a typo does not help, because the whole file was rejected before any line executed. There are exceptions, and they matter, since they are where SyntaxError shows up inside working programs: JSON.parse(), eval(), new Function(), new RegExp() and dynamic import() all read text at run time and throw it. This post covers when you can and cannot catch it, the JSON.parse failures that make up most of the cases, the code-level messages and their fixes, strict mode and module rules, and how to report parse errors to a user. The messages come from V8, which runs Node.js 24 and Chrome, and other engines word them differently.

Why try and catch does not help

JavaScript
console.log("this line never runs");

try {
  const broken = ;
} catch (e) {
  console.log("caught", e.name);
}
Text
/path/to/file.js:4
  const broken = ;
                 ^

SyntaxError: Unexpected token ';'

The file is a script with an error at the declaration. Node.js reads the whole file first, prints the file name, the line and a caret under the problem (followed by a stack trace and the Node.js version, left out above), and exits before the first console.log runs. The try is irrelevant, because the engine never reached it. The only place such an error can appear in your own source is at load time, which means the fix is to read the message and the line number, correct the text, and run again. An editor or node --check file.js finds these without running the code.

Errors you can catch: text read at run time

The same engine rules apply to code that is built as a string, and then the error is thrown while the program runs and can be caught.

JavaScript
const sources = [
  "1 +",
  "let a; let a;",
  "return 1",
  "const = 5",
  "console.log('a'",
  "await 1",
];

for (const source of sources) {
  try {
    new Function(source);
    console.log("ok:", source);
  } catch (e) {
    console.log(e.name, "|", e.message);
  }
}
Text
SyntaxError | Unexpected end of input
SyntaxError | Identifier 'a' has already been declared
ok: return 1
SyntaxError | Unexpected token '='
SyntaxError | missing ) after argument list
SyntaxError | await is only valid in async functions and the top level bodies of modules

new Function() only parses the body, it does not run it, and it wraps the text in a function, so return 1 is valid there. Each message names what the parser found and where it gave up. Executing strings of code is a security risk and almost never needed, so treat these as a demonstration of the error, and not a pattern. The practical cases are the ones in the next sections.

JSON.parse is the common one

JSON is a stricter language than JavaScript object syntax, and every mistake is a SyntaxError.

JavaScript
const inputs = [
  '{"name": "Ada"}',
  "{'name': 'Ada'}",
  '{"name": "Ada",}',
  "",
  "undefined",
  '{"a": 1} extra',
  "<!DOCTYPE html>",
];

for (const text of inputs) {
  try {
    JSON.parse(text);
    console.log("ok");
  } catch (e) {
    console.log(e.name, "|", e.message);
  }
}
Text
ok
SyntaxError | Expected property name or '}' in JSON at position 1 (line 1 column 2)
SyntaxError | Expected double-quoted property name in JSON at position 15 (line 1 column 16)
SyntaxError | Unexpected end of JSON input
SyntaxError | "undefined" is not valid JSON
SyntaxError | Unexpected non-whitespace character after JSON at position 9 (line 1 column 10)
SyntaxError | Unexpected token '<', "<!DOCTYPE "... is not valid JSON

The messages in recent V8 versions include the position, which is the first thing to check. Single quotes, a trailing comma and a bare undefined are all valid in JavaScript and invalid in JSON. The last entry is the classic production failure: an HTTP request that was supposed to return JSON returned an HTML error page, and the parser stopped at the first <. The text of the response, not the parser, is the thing to examine. An empty string is also an error, which is how an empty response body becomes Unexpected end of JSON input.

A parse helper that reports well

JavaScript
function parseJson(text) {
  try {
    return { ok: true, value: JSON.parse(text) };
  } catch (error) {
    if (!(error instanceof SyntaxError)) throw error;
    return { ok: false, message: error.message, preview: String(text).slice(0, 20) };
  }
}

console.log(parseJson('{"a": 1}'));
console.log(parseJson("{oops"));
console.log(parseJson("<html>"));
Text
{ ok: true, value: { a: 1 } }
{
  ok: false,
  message: "Expected property name or '}' in JSON at position 1 (line 1 column 2)",
  preview: '{oops'
}
{
  ok: false,
  message: `Unexpected token '<', "<html>" is not valid JSON`,
  preview: '<html>'
}

The helper catches only SyntaxError and rethrows anything else, so a real bug is not hidden. It returns the message and a short preview of the input, which is what a log line needs to be useful. For a user-facing error, do not show the engine's message: say that the data could not be read and keep the details in the log. Do not log the full text if it may contain secrets.

Regular expressions

A pattern built at run time can be invalid, and it throws a SyntaxError when the RegExp is created.

JavaScript
for (const pattern of ["(", "[a-", "a{2,1}", "*a", "(?<n>a)(?<n>b)", "\\p{L}"]) {
  try {
    new RegExp(pattern, "u");
    console.log(JSON.stringify(pattern), "ok");
  } catch (e) {
    console.log(JSON.stringify(pattern), e.name);
  }
}
Text
"(" SyntaxError
"[a-" SyntaxError
"a{2,1}" SyntaxError
"*a" SyntaxError
"(?<n>a)(?<n>b)" SyntaxError
"\\p{L}" ok

Each of the first five is a pattern the parser rejects: an unclosed group, an unclosed class, a range in the wrong order, a quantifier with nothing to repeat and a duplicate group name. Patterns that come from users must go through try, or be escaped with RegExp.escape(), covered in JavaScript RegExp.escape, so that their text is matched literally.

Strict mode and modules add rules

Some code is valid in a script and a syntax error in strict mode or in a module.

JavaScript
const snippets = [
  '"use strict"; 010',
  '"use strict"; with ({}) {}',
  '"use strict"; var let = 1',
  '"use strict"; function f(a, a) {}',
  "with ({}) {}",
  "var let = 1",
];

for (const source of snippets) {
  try {
    new Function(source);
    console.log("ok:", source);
  } catch (e) {
    console.log(e.name, "|", source);
  }
}
Text
SyntaxError | "use strict"; 010
SyntaxError | "use strict"; with ({}) {}
SyntaxError | "use strict"; var let = 1
SyntaxError | "use strict"; function f(a, a) {}
ok: with ({}) {}
ok: var let = 1

Legacy octal numbers, the with statement, reserved words as names and duplicate parameter names are all permitted in sloppy mode and rejected in strict mode. ES modules and class bodies are always strict, so code that ran as a script can fail the moment it is moved into a module. The error message names the construct, and the fix is to modernize it: write octal as 0o10, avoid with, and rename the variable.

Module-specific messages

Node.js treats a file as CommonJS or as an ES module depending on its extension and package.json, and using the wrong syntax gives a SyntaxError.

JavaScript
const sources = [
  'import fs from "node:fs";',
  "export const a = 1;",
  "const x = await Promise.resolve(1);",
];

for (const source of sources) {
  try {
    new Function(source);
    console.log("ok");
  } catch (e) {
    console.log(e.message);
  }
}
Text
Cannot use import statement outside a module
Unexpected token 'export'
await is only valid in async functions and the top level bodies of modules

These are the three messages people meet when a project mixes module formats. In a real file the fix is to use the .mjs extension or set "type": "module" in package.json, so Node.js reads the file as an ES module. Inside an async function, await is allowed anywhere. At the top level of a CommonJS file it is not.

Common messages and what they mean

MessageUsual cause
Unexpected token 'x'A character in the wrong place, often a missing comma or bracket nearby
Unexpected end of inputAn unclosed (, [, { or string
Unexpected identifierTwo names in a row, a missing operator or comma
missing ) after argument listA missing comma or closing parenthesis in a call
Invalid or unexpected tokenA stray character, a smart quote or an unclosed string
Identifier has already been declaredTwo let or const with the same name in one scope
Unexpected token in JSONSingle quotes, a trailing comma or an HTML response

The position the engine reports is where it gave up, which can be after the real mistake. A missing closing brace in one function is often reported at the end of the file, and a missing comma in an object literal is reported at the next property. Look at the line before the one named.

A mistake we hit: smart quotes and invisible characters

JavaScript
const good = 'He said "hi"';
const withSmartQuote = "const t = \u201Chello\u201D;";
const withBom = "\uFEFFconst a = 1;";
const withZeroWidth = "const\u200Ba = 1;";

for (const [label, source] of [["smart quote", withSmartQuote], ["bom", withBom], ["zero-width space", withZeroWidth], ["plain", good]]) {
  try {
    new Function(source);
    console.log(label, "ok");
  } catch (e) {
    console.log(label, e.name);
  }
}
Text
smart quote SyntaxError
bom ok
zero-width space SyntaxError
plain ok

Curly quotes from a document or a chat window look like quotes and are not, and a zero-width space looks like nothing at all and still breaks the code. Both are SyntaxErrors with the unhelpful message Invalid or unexpected token. A byte order mark at the start of a file is allowed, and so is a non-breaking space, which JavaScript treats as ordinary whitespace. We lost an hour to a configuration snippet pasted from a wiki that contained a zero-width space inside a variable name. Searching the file for non-ASCII characters finds them: grep -nP '[^\x00-\x7F]' file.js.

Choosing between the fixes

You seeDo this
The program does not start and prints a file and lineFix the text at that line; run node --check
A SyntaxError from JSON.parseLog the start of the text; check the response is JSON
A SyntaxError from new RegExpEscape user text, and wrap pattern building in try
Works as a script, fails as a moduleRemove sloppy-mode constructs
Cannot use import statement outside a moduleUse .mjs or "type": "module"
Invalid or unexpected tokenLook for smart quotes and zero-width characters

Practical rules we follow

Run a linter or node --check in the editor and in CI, so typos never reach a run. Wrap JSON.parse in a helper that catches only SyntaxError. Check the content type before parsing a response. Never build code from strings. Escape user text before putting it in a pattern. And never show a parse message to an end user: log it, and show a sentence that tells them what to do.

Where SyntaxError stops being the right diagnosis

It says the text did not parse, and does not say what the writer meant. A single missing character can produce an error far from the real mistake. It is separate from TypeError and ReferenceError, which are about values and names at run time. And JSON parse failures often have nothing to do with your code: the other side sent something that was not JSON. The reference is in the MDN SyntaxError page and the ECMAScript specification.

Taggederrors
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.