How to catch syntax errors in JavaScript?

In this tutorial, we will learn how to catch syntax errors in JavaScript and handle them effectively.

JavaScript throws various types of errors when we write incorrect code: ReferenceError when calling undefined variables, TypeError when trying to modify immutable values inappropriately, and SyntaxError when the code structure is invalid.

What is Syntax Error?

A SyntaxError occurs when JavaScript encounters code that violates the language's syntax rules. Unlike runtime errors, syntax errors are detected during the parsing phase, before the code executes.

Common Causes of Syntax Errors

  • Missing brackets: Unclosed parentheses (), braces {}, or square brackets []
  • Missing quotes: Unterminated string literals
  • Misspelled keywords: Incorrect function names or reserved words
  • Invalid characters: Special characters in wrong places

These errors appear in the browser's developer console with descriptive messages and line numbers.

Example: Missing Quote SyntaxError

<!DOCTYPE html>
<html>
<body>
   <h1>SyntaxError Example</h1>
   <p id="result"></p>
   <script>
      var message = "Hello world!";
      document.getElementById("result).innerHTML = message;  // Missing closing quote
   </script>
</body>
</html>

This code throws: "Uncaught SyntaxError: Invalid or unexpected token" because of the missing closing quote in "result.

Why try-catch Cannot Handle SyntaxErrors

Unlike runtime errors, SyntaxErrors cannot be caught using try-catch blocks because they occur during the parsing phase, before any JavaScript code executes.

try {
    eval('var x = "unclosed string;');  // SyntaxError in eval
} catch (error) {
    console.log("Caught:", error.name);  // This works only with eval
}
Caught: SyntaxError

Using window.onerror() for Global Error Handling

The window.onerror() function catches uncaught exceptions and syntax errors globally, providing error details for debugging.

Syntax

window.onerror = function(message, source, lineno, colno, error) {
    // Handle error
    return true; // Prevents default browser error handling
};

Parameters

  • message: Error description
  • source: URL of the file containing the error
  • lineno: Line number where error occurred
  • colno: Column number (optional)
  • error: Error object (optional)

Example: Catching SyntaxError with onerror()

<!DOCTYPE html>
<html>
<body>
   <h2>SyntaxError Handling with onerror()</h2>
   <p id="result"></p>
   <script>
      window.onerror = function(message, source, lineno) {
         document.getElementById('result').innerHTML = 
            'Error: ' + message + ' at line ' + lineno;
         return true;  // Prevent default error handling
      };
   </script>
   <script>
      var message = "Hello World!;  // Missing closing quote
   </script>
</body>
</html>

Simplified Error Handler

<!DOCTYPE html>
<html>
<body>
   <h2>Simple SyntaxError Handler</h2>
   <p id="result"></p>
   <script>
      window.onerror = function(error) {
         document.getElementById('result').innerHTML = "Error detected: " + error;
      };
   </script>
   <script>
      var message = "Hello World!;  // Syntax error here
   </script>
</body>
</html>

Best Practices

  • Define window.onerror in a separate script tag before other scripts
  • Use code linters (ESLint) to catch syntax errors during development
  • Test code in browser dev tools before deployment
  • Return true from onerror to prevent default browser error display

Conclusion

SyntaxErrors occur during parsing and cannot be caught with try-catch. Use window.onerror() for global error handling and proper development tools to prevent syntax errors before deployment.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements