JavaScript Syntax Errors and How to Prevent Them

updated on 23 May 2022

Syntax errors are a constant problem for programmers. A missing parenthesis or bracket can stop your code from compiling or executing, leading to lost work time and frustration. Other common errors include missing quotation marks or commas, or even using the wrong syntax entirely.

The best solution to this problem is to prevent syntax errors from happening in the first place. If you stay alert for the most common errors, you can correct them before deployment. There are also various automated tools that can do this detection work for you.

In this article, you’ll learn more about syntax errors in JavaScript. You’ll see some examples of common syntax errors, along with techniques and tools on how to fix them and keep them out of your code.

Why Do You Need to Know about Syntax Errors?

Syntax errors, also known as parse errors, occur in JavaScript when developers incorrectly use a predefined structure or language pattern. The typos or other mistakes result in invalid code. These errors include open or mismatched brackets, missing parentheses or punctuation, or misspelled keywords.

The following are some of the reasons why you need to know about syntax errors:

- A program will not successfully compile or run until all syntax errors have been corrected. Avoiding this kind of error can help you achieve more efficient and accurate coding.

- It’s easy to reduce the occurrence of this error if you know about it. Browser developer tools display JavaScript syntax errors in the console and also indicate the line in the code where the error occurs, giving you an idea of where to start looking. 

- Syntax errors will typically prevent build tools from being able to run, meaning you cannot build or deploy your application. If there is no build process and the raw JavaScript is deployed, these errors will happen at runtime.

What Are Some Common Syntax Errors?

The following are some examples of syntax errors that commonly cause trouble for developers.

Missing or Unmatched Quotation Marks

Quotation marks are a frequent cause of problems. Errors include adding an opening quotation mark without closing it or trying to close off a double quotation mark with a single quotation mark (or vice versa). Adding more quotation marks than needed will also cause a syntax error because the additional quotes will be unmatched.

For example:

let arr = ["Joy", "Ruby", "Gail]   // Missing a quotation mark for the last item

Open or Mismatched Brackets

Another common mistake is having an open bracket without a matching closing bracket. Trying to close off an open curly bracket with a square bracket or vice versa will also cause this error.

For example:

function check(x){
    if(x === 10){
      return true
    } else {
      return false
    // Missing a closing curly bracket
  }

Also:

let arr = [
    {
        "name": "Lynn"
    },
    {
        "name": "Ruby"
    },
    {
        "name": "Phil"
    }
    }   // Should be a closing square bracket

Missing Commas

You’ll get a syntax error if you forget to add commas between items in arrays or objects:

let arr ["apple", "orange" "pear"]   // Missing a comma

Missing Semicolons

Forgetting semicolons where they are expected, for instance in a for loop, is another cause of syntax errors in JavaScript:

let arr = [0, 1, 2, 3]
for(let i =0; i <= arr.length i++){   // Missing a semicolon after the second statement
  console.log(arr[i] * 2)
}

Missing Parentheses

It’s an easy mistake to leave off a closing parenthesis in scenarios where you have nested blocks of code, such as in a nested if statement:

function check(x, y){
    if((x === 10) && (y ===5){   // Missing closing parenthesis; should be if((x === 10) && (y ===5)){...
        return true
    } else {
      return false
     }
}

Multilingual Syntactic Confusion

As your stack grows and you learn more programming languages, you might mistakenly try to use syntax for another language in JavaScript. You need to remember JavaScript’s rules and be mindful of them when coding.

The example below includes a while loop that follows Python syntax, which will cause an error when used in JavaScript:

function check(x){
    while(x > 5):
     return x + 1
}

How Can You Prevent These Errors?

There are several tools and best practices you can use to keep syntax errors out of your code. The following are some examples.

Code Editors or IDEs

These tools offer functionalities to help you write and debug code. Features include code autocompletion, which reduces the likelihood of you missing a closing bracket or parenthesis, and syntax highlighting, which uses specific colors to alert you to syntax errors in your code.

In the first image below, you’ll see a syntax error highlighted in Visual Studio Code; in the second, you’ll see how the code editor looks when the error is fixed:

1-u61dt
2-jryqu

Note that while most code editors come with built-in features to help with debugging, some of these features work by default while some might require you to change basic configuration or settings first.

Static Code Analysis Tools

Static code analysis tools help detect errors and potential problems in continuous integration (CI) workflows before code is released to production. The tools scan your code and compare it to predefined rules to find errors. ESLint and JSLint are examples of static code analysis tools.

ESLint allows you to apply rules that can be used to draw attention to specific patterns, but it may have difficulty with some syntax errors. Depending on what rules you have configured, malformed function declarations like function foo () {}} can make the code unparsable. Since the code cannot be read or interpreted correctly, ESLint will stop highlighting other issues.

TypeScript

TypeScript can help provide insights into syntax errors and how to solve them. Instead of testing and encountering errors at runtime, you can use the TypeScript compiler to display errors in the terminal during compile time.

3-y8rqz

Indentation

Indenting your code is a standard practice that makes it easier to read the code and spot missing brackets or parentheses. Tools like Prettier, ESLint, and Beautify can help you format your code properly, making it more legible with consistent formatting, thereby improving code quality.

Challenges of Preventing Errors

Sometimes syntax errors will make it difficult to read or interpret code correctly, hindering the effectiveness of certain tools.

Additionally, statements like function foo () {}} can cause errors that will stop tools like Prettier from being able to parse and format your code, because these tools do not validate syntax. They would need to be able to parse the code before reprinting with their own rules.

How Meticulous Can Help

Meticulous is a tool that can catch JavaScript errors before your code goes to production so that you don’t ship errors with your application. 

Meticulous helps you catch JavaScript errors before they reach your users. It does this by letting you record sessions and then play them back against new versions of your code as you continue to make changes. In this way, you can easily detect regressions and identify errors before they ever reach your customers in production.

For more on how Meticulous can help you, consult the documentation.

Conclusion

Even the smallest errors can cause big problems in your code. As you learned in this article, you need to be able to detect syntax errors in your JavaScript applications so that your linting and other tools which rely on parsing can give you feedback on your code, and so that you can deploy and ship it.

If you keep these tips and tools in mind as you write code, you should be able to find and fix these problems. This will improve the quality of your software and speed up your workflow.

Authored by Goodness Chris-Ugari

Read more