Open In App

JavaScript SyntaxError – Illegal character

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

This JavaScript exception illegal character occurs if there is an invalid or unexpected token that doesn’t belong there in the code.

Understanding an error

An “Unexpected token ILLEGAL” error signifies that there is an invalid character present within the code, in certain situations, JavaScript requires particular characters, however should one occur which is not supposed to be there, then it causes SyntaxError because language rules are broken.

Case 1: Typographical Mistakes

Error Cause:

Typographical errors, for example the use of invalid characters or symbols can give an “Unexpected token ILLEGAL” error.

Example:

JavaScript
let name = "GeeksForGeeks�";
console.log(name);


Output:

SyntaxError: Unexpected token ILLEGAL

Resolution of error

All characters should be checked to ensure that they are valid and used properly especially those which are not properly visible.

JavaScript
let name = "GeeksForGeeks";
console.log(name);

Output
GeeksForGeeks

Case 2: Invalid Escape Sequences

Error Cause:

The strings with wrong escape sequences may cause for an Unexpected token ILLEGAL error.

Example:

JavaScript
let path = "C:\new_folder\file.txt";
console.log(path);

Output:

SyntaxError: Unexpected token ILLEGAL

Resolution of error

For special characters one should apply the correct escape sequences.

JavaScript
let path = "C:\\new_folder\\file.txt";
console.log(path);

Output
C:\new_folder\file.txt

Case 3: Using non-ASCII Characters

Error Cause:

Non-ASCII character inclusion, such as invisible and special symbol causes an “Unexpected token ILLEGAL” error.

Example:

JavaScript
function myFunction(a, b) { // Contains an invisible character
    return a + b;
}

Output:

SyntaxError: Unexpected token ILLEGAL

Note: The parameter in the above code which looks like ‘a’ it is actually a non-ASCII character.

Untitled

Using non-ASCII Characters

Resolution of error

You have to remove or replace non-ASCII characters with their valid equivalent.

JavaScript
function myFunction(a, b) {
    return a + b;
}

console.log(myFunction(2, 3));

Output
5

To keep the integrity of your program intact in JavaScript so as to avoid “Unexpected token ILLEGAL” errors while using it, all words in a code must follow JavaScript syntax rules, check for typos, use valid escape sequences, prevent hiddenness and remove non-ASCII, this will maintain code integrity and functionality.


Next Article

Similar Reads