The Problem

When writing JavaScript code, you might encounter the SyntaxError: Unterminated string literal (or in some browsers, Uncaught SyntaxError: Invalid or unexpected token). This error means that a string literal was not properly terminated. It usually occurs when there is an opening quote for a string but no closing quote, or when an invalid character is used within the string.

// Incorrect Example 1: Missing closing quote
let message = 'Hello, world;

// Incorrect Example 2: Line break inside a string
let htmlString = '<div>
    <p>Hello</p>
</div>';

console.log(message);
console.log(htmlString);

Both of the above code snippets will cause a SyntaxError. The first one is missing a closing single quote ('). The second one includes a direct line break within a regular string.

Cause Analysis

The main causes of this error are:

  1. Mismatched or Missing Quotes: The closing quote does not match the opening quote (single ' vs. double `

Leave a comment