JavaScript SyntaxError: Unterminated string literal
This JavaScript error unterminated string literal occurs if there is a string that is not terminated properly. String literals must be enclosed by single (') or double (") quotes.
Message:
SyntaxError: Unterminated string constant (Edge)
SyntaxError: unterminated string literal (Firefox)
Error Type:
SyntaxError
What happened?
There is a string in the code which is not terminated. String literals need to be enclosed by single (') or double (") quotes. JavaScript sees no difference between single-quoted strings and double-quoted strings.
Case 1: Missing Closing Quote
Error Cause:
If you start a string with a quote but forget to close it with another matching quote, you'll get an "Unterminated string literal" error.
Example:
let greeting = "Hello, World;
console.log(greeting);
Output:
SyntaxError: Unterminated string literal
Resolution:
Ensure that all string literals are properly enclosed with matching quotes.
let greeting = "Hello, World";
console.log(greeting);
Output
Hello, World
Case 2: Unescaped Quote Inside a String
Error Cause:
If you use quotes inside a string without escaping them, it may cause the interpreter to mistakenly think the string has ended.
Example:
let message = "He said, "Hello!";
console.log(message);
Output:
SyntaxError: Unterminated string literal
Resolution:
Escape the internal quotes or use a different type of quote to enclose the string.
let message = "He said, \"Hello!\"";
console.log(message);
Output
He said, "Hello!"
Case 3: Improper Use of Template Literals
Error Cause:
If using template literals (enclosed by backticks) but forget to close them, you will encounter an unterminated string literal error.
Example:
let template = `This is a template literal;
console.log(template);
Output:
SyntaxError: Unterminated string literal
Resolution:
Ensure that all template literals are properly closed with backticks.
let template = `This is a template literal`;
console.log(template);
Output
This is a template literal