Categories
JavaScript Answers

How to Fix the ‘SyntaxError: illegal character ‘ Error in Our JavaScript App?

Spread the love

Sometimes, we may run into the ‘SyntaxError: illegal character’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘SyntaxError: illegal character’ when we’re developing JavaScript apps.

Fix the ‘SyntaxError: illegal character’ When Developing JavaScript Apps

To fix the ‘SyntaxError: illegal character’ when we’re developing JavaScript apps, we should make sure we didn’t have any characters that the JavaScript doesn’t accept in out code.

On Edge, the error message for this error is SyntaxError: Invalid character.

On Firefox, the error message for this error is SyntaxError: illegal character.

And on Chrome, the error message for this error is SyntaxError: Invalid or unexpected token.

For instance, the following code will throw the error:

“This looks like a string”;
2 – 13; 
let foo = 'bar';

In the first line, the and characters aren’t the same as the double quote characters accepted by JavaScript engines, which is ".

In the 2nd line, isn’t the same as the minus sign, which is -.

And in the last line, ; is the <37e> character, which isn’t the same as the semicolon accepted by JavaScript.

To fix this, we write:

"This is a string";
42 - 13;
let foo = 'bar';

This error is also thrown when we forgot some character.

For instance, the error will be thrown when we write:

const colors = ['#000', white', '#666'];

We forgot the opening single quote in the 2nd string.

To fix this, we write:

const colors = ['#000', 'white', '#666'];

We should also remove hidden characters that may cause this error,

For instance, the following code:

const foo = 'bar';

has a zero-width space at the end. Once we remove it, then the code runs.

Conclusion

To fix the ‘SyntaxError: illegal character’ when we’re developing JavaScript apps, we should make sure we didn’t have any characters that the JavaScript doesn’t accept in out code.

On Edge, the error message for this error is SyntaxError: Invalid character.

On Firefox, the error message for this error is SyntaxError: illegal character.

And on Chrome, the error message for this error is SyntaxError: Invalid or unexpected token.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *