SyntaxError in JavaScript: malformed code or malformed JSON

A SyntaxError happens when the text being read breaks the grammar of the language: why it precedes execution, and the very common JSON.parse case.
3 min read
Believemy logo

This error has a peculiarity that sets it apart from all the others: most of the time it happens before a single line has run.

Which explains a behavior that puzzles everyone the first time. A try carefully wrapped around the offending code catches absolutely nothing.


Definition

A SyntaxError is thrown when a piece of text breaks the expected grammar. Two very different moments produce one: parsing a file before it runs, and parsing a string while it runs.

MomentExampleCatchable?
While parsing the fileAn unclosed braceNo, the whole file is rejected
While runningJSON.parse, new FunctionYes, by an ordinary try

Those three columns sum up the whole subject. The first case is fixed in the editor, the second is handled in the code.


Why the try is useless

The engine reads the entire file before running its first statement. If parsing fails, nothing starts: not the try, not the catch, not even the lines above them.

JAVASCRIPT
// This file does not run at all: the SyntaxError happens at parse time
// try {
//   const = 3;
// } catch (err) {
//   console.log("never printed");
// }

// Here the error is properly caught: the string is parsed while running
try {
  new Function("const = 3");
} catch (err) {
  console.log(err.name);   // SyntaxError
}


JSON.parse, the most frequent case

In practice, the SyntaxError met in production nearly always comes from JSON. A truncated server response, an HTML error page served in place of the data, an empty value: the content is not valid JSON.

JAVASCRIPT
const samples = ["{}", "", "{a:1}", "undefined"];

for (const text of samples) {
  try {
    JSON.parse(text);
    console.log("valid:", text);
  } catch (err) {
    console.log("invalid:", JSON.stringify(text), "|", err.message);
  }
}

// valid: {}
// invalid: "" | Unexpected end of JSON input

A catch around every parse is therefore mandatory as soon as the text comes from outside: network, file, local storage or user input.

Good to know

A message starting with "Unexpected token <" is a classic: the server returned an HTML page, often an error page or a login redirect. Check the status code of the response before calling JSON.parse, and the error turns talkative.


Frequently asked questions

Question

Is the reported line number reliable?

It points to where the parser realized something was wrong, which is not always where the mistake is. A brace forgotten fifty lines above often gets reported at the end of the file: work upward from the reported point rather than staring at the line named.


Question

Why does recent syntax trigger this error?

Because the environment reading the file is older than the syntax being used. An outdated browser or too low a Node.js version does not know the construct and rejects it at parse time. Transpilation exists precisely to rewrite the code in an older syntax.


Question

How do you avoid writing them?

By letting the tooling take care of it. An automatic formatter catches the vast majority of these mistakes on save, and the editor underlines the orphaned brace before you even save. The authoring SyntaxError is the easiest one to remove from a development workflow.

Related terms

Discover our javaScript glossary

Every word of JavaScript explained simply: keywords, built-in objects, methods, errors and concepts. Clear definitions and examples that actually run, to learn and to troubleshoot.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.