No visible cause for "Unexpected token ILLEGAL"
Asked Answered
A

11

274

I'm getting this JavaScript error on my console:

Uncaught SyntaxError: Unexpected token ILLEGAL

This is my code:

var foo = 'bar';​

It's super simple, as you can see. How could it be causing a syntax error?

Amaras answered 4/10, 2012 at 3:23 Comment(4)
For future readers: if you encountered this error when using Vagrant - this answer also can be helpful: #9479617Charette
In the event that you are experiencing this in WordPress, enqueue the scripts from functions.php. I had a specific template where I was calling for the JS directly from the template. Switching to a conditional enqueue in either wp_head or wp_footer resolved this.Antitoxin
Moderator's Note: I deleted a bunch of answers here that don't actually answer the question. This is not, I repeat not, a place to list every possible thing you can do in JavaScript that will result in this error. The question has a very specific circumstance that does not involve any of those scenarios, and all those examples simply do not answer the question.Henebry
Wow, the SO police had a field day with this question. Luckily, some of the relevant information is still visible in the deleted answers.Demoniac
A
496

The error

When code is parsed by the JavaScript interpreter, it gets broken into pieces called "tokens". When a token cannot be classified into one of the four basic token types, it gets labelled "ILLEGAL" on most implementations, and this error is thrown.

The same error is raised if, for example, you try to run a js file with a rogue @ character, a misplaced curly brace, bracket, "smart quotes", single quotes not enclosed properly (e.g. this.run('dev1)) and so on.

A lot of different situations can cause this error. But if you don't have any obvious syntax error or illegal character, it may be caused by an invisible illegal character. That's what this answer is about.

But I can't see anything illegal!

There is an invisible character in the code, right after the semicolon. It's the Unicode U+200B Zero-width space character (a.k.a. ZWSP, HTML entity ​). That character is known to cause the Unexpected token ILLEGAL JavaScript syntax error.

And where did it come from?

I can't tell for sure, but my bet is on jsfiddle. If you paste code from there, it's very likely to include one or more U+200B characters. It seems the tool uses that character to control word-wrapping on long strings.

UPDATE 2013-01-07

After the latest jsfiddle update, it's now showing the character as a red dot like codepen does. Apparently, it's also not inserting U+200B characters on its own anymore, so this problem should be less frequent from now on.

UPDATE 2015-03-17

Vagrant appears to sometimes cause this issue as well, due to a bug in VirtualBox. The solution, as per this blog post is to set sendfile off; in your nginx config, or EnableSendfile Off if you use Apache.

It's also been reported that code pasted from the Chrome developer tools may include that character, but I was unable to reproduce that with the current version (22.0.1229.79 on OSX).

How can I spot it?

The character is invisible, do how do we know it's there? You can ask your editor to show invisible characters. Most text editors have this feature. Vim, for example, displays them by default, and the ZWSP shows as <u200b>. You can also debug it online: jsbin displays the character as a red dot on its code panes (but seems to remove it after saving and reloading the page). CodePen.io also displays it as a dot, and keeps it even after saving.

Related problems

That character is not something bad, it can actually be quite useful. This example on Wikipedia demonstrates how it can be used to control where a long string should be wrapped to the next line. However, if you are unaware of the character's presence on your markup, it may become a problem. If you have it inside of a string (e.g., the nodeValue of a DOM element that has no visible content), you might expect such string to be empty, when in fact it's not (even after applying String.trim).

ZWSP can also cause extra whitespace to be displayed on an HTML page, for example when it's found between two <div> elements (as seen on this question). This case is not even reproducible on jsfiddle, since the character is ignored there.

Another potential problem: if the web page's encoding is not recognized as UTF-8, the character may actually be displayed (as ​ in latin1, for example).

If ZWSP is present on CSS code (inline code, or an external stylesheet), styles can also not be parsed properly, so some styles don't get applied (as seen on this question).

The ECMAScript Specification

I couldn't find any mention to that specific character on the ECMAScript Specification (versions 3 and 5.1). The current version mentions similar characters (U+200C and U+200D) on Section 7.1, which says they should be treated as IdentifierParts when "outside of comments, string literals, and regular expression literals". Those characters may, for example, be part of a variable name (and var x\u200c; indeed works).

Section 7.2 lists the valid White space characters (such as tab, space, no-break space, etc.), and vaguely mentions that any other Unicode “space separator” (category “Zs”) should be treated as white space. I'm probably not the best person to discuss the specs in this regard, but it seems to me that U+200B should be considered white space according to that, when in fact the implementations (at least Chrome and Firefox) appear to treat them as an unexpected token (or part of one), causing the syntax error.

Amaras answered 4/10, 2012 at 3:23 Comment(15)
codepen.io also appears to display this character. VIM and VI, also notepad++ displays it.Avner
Thanks @rlemon, added a CodePen example to the answer. Nice site, I didn't know about it.Amaras
Ran into this very problem while copy/pasting code for the testTwo class from this SO question using Chromium. Apparently, the parser choked on the syntax highlighting of the function keyword, which was invisible in Vim until I highlighted it using the "Highlight all non-printable chars" FAQ method. Ahh it would be so nice if there was a way to only copy chars in the range of 32..127 (but there's probably an app for that :) )Vaginate
I had an array that I was using wordwrap on in Vim and encountered this error as a result. Thanks!Prochoras
this is the solution, well explained. In my case I had some JSON code into a variable and formatted with return and spaces. I had to remove all the returns and spaces and it worked.Abessive
More characters that I found that can break the JSON are \u2028 and \u2029Pater
In Chrome Dev Tools the character is also shown as a red dotEnthuse
@bfavaretto, code snippet into question too displays the character as a red dot.Favored
@Fernando I don't see that in Chrome. Which browser did you test with?Amaras
@bfavaretto, only in the code snippet in edit mode. Not in the body of the question, should have mentioned this. (Tested on Chrome 43.0.2357.124 m)Favored
Interestingly, I ran into this problem when initializing a js variable containing a hardcoded html string with a nested script tag inside the string. No complaints after the script tag was removed from the string (had no good reasons to put it in there anyway).Dodecanese
@kevinze See Why split the <script> tag when writing it with document.write()?Amaras
plus 1 to you! Zapped all the gremlins (aka illegal characters) ... and now it works!Irfan
I encountered the same error but in my case it was a nginx permission issue . Found the solution here serverfault.com/questions/315085/…Sweepings
Many text editors allow switching the character encoding of a file. This is tremendously useful to find offending characters like these. My solution was to temporarily switch from UTF-8 to an ANSI encoding, remove the invalid characters, then switch back. I used the freeware Notepad++ on Windows. EDIT: Turns out I missed the Notepad++ option for "Displaying All Characters". Same result, less hassle :DStormystorting
D
64

why you looking for this problem into your code? Even, if it's copypasted.

If you can see, what exactly happening after save file in synced folder - you will see something like ***** at the end of file. It's not related to your code at all.

Solution.

If you are using nginx in vagrant box - add to server config:

sendfile off;

If you are using apache in vagrant box - add to server config:

EnableSendfile Off;

Source of problem: VirtualBox Bug

Disinfectant answered 6/5, 2014 at 6:15 Comment(6)
You literally saved my day. I've struggled with Nginx + Vagrant for a whole evening, and this solved it.Feed
Did NOT expect this to be the right answer (for me) but it was, thanks so much.Rattler
Actually, it stopped working. Then again there're multiple layers of symlinking at play here so I just undid what I could.Rattler
Thanks - I was in a vagrant box with nginx. I've also seen this issue on similar Apache setups.Triturate
for apache: EnableSendfile OffAlyssaalyssum
Thank you very much! I thought that it was something with gulp or webpack. I never thought that this is a problem with vagant!Virgule
A
7

This also could be happening if you're copying code from another document (like a PDF) into your console and trying to run it.

I was trying to run some example code out of a Javascript book I'm reading and was surprised it didn't run in the console.

Apparently, copying from the PDF introduces some unexpected, illegal, and invisible characters into the code.

Aperiodic answered 28/1, 2014 at 16:10 Comment(0)
L
5

I had the same problem on my mac and found it was because the Mac was replacing the standard quotes with curly quotes which are illegal javascript characters.

To fix this I had to change the settings on my mac System Preferences=>Keyboard=>Text(tab) uncheck use smart quotes and dashes (default was checked).

Langmuir answered 2/4, 2015 at 13:46 Comment(0)
E
5

I got this error in chrome when I had an unterminated string after the line that the error pointed to. After closing the string the error went away.

Example with error:

var file = files[i]; // SyntaxError: Unexpected token ILLEGAL

jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
    + "<a href=\"javascript: something('"+file.id+');\">Error is here</a>";

Example without error:

var file = files[i]; // No error

jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
    + "<a href=\"javascript: something('"+file.id+"');\">Error was here</a>";
Equisetum answered 20/9, 2015 at 16:22 Comment(1)
I had to run a diff on your two examples to figure out the difference, and once I did I immediately figured out my own issue.Cowman
D
3

If you are running a nginx + uwsgi setup vagrant then the main problem is the Virtual box bug with send file as mentioned in some of the answers. However to resolve it you have to disable sendfile in both nginx and uwsgi.

  1. In nginx.conf sendfile off

  2. uwsgi application / config --disable-sendfile

Dianoia answered 23/3, 2015 at 19:39 Comment(0)
A
2

When running OS X, the filesystem creates hidden forks of basically all your files, if they are on a hard drive that doesn't support HFS+. This can sometimes (happened to me just now) lead to your JavaScript engine tries to run the data-fork instead of the code you intend it to run. When this happens, you will also receive

SyntaxError: Unexpected token ILLEGAL

because the data fork of your file will contain the Unicode U+200B character. Removing the data fork file will make your script run your actual, intended code, instead of a binary data fork of your code.

.whatever : These files are created on volumes that don't natively support full HFS file characteristics (e.g. ufs volumes, Windows fileshares, etc). When a Mac file is copied to such a volume, its data fork is stored under the file's regular name, and the additional HFS information (resource fork, type & creator codes, etc) is stored in a second file (in AppleDouble format), with a name that starts with ".". (These files are, of course, invisible as far as OS-X is concerned, but not to other OS's; this can sometimes be annoying...)

Alenealenson answered 15/2, 2016 at 15:9 Comment(0)
E
1

Here is my reason:

before:

var path = "D:\xxx\util.s"

which \u is a escape, I figured it out by using Codepen's analyze JS.

after:

var path = "D:\\xxx\\util.s"

and the error fixed

Ex answered 9/8, 2016 at 14:22 Comment(0)
A
0

I had this same problem and it occurred because I had hit the enter key when adding code in a text string.

Because it was a long string of text I wanted to see it all without having to scroll in my text editor, however hitting enter added an invisible character to the string which was illegal. I was using Sublime Text as my editor.

Apps answered 11/12, 2015 at 18:58 Comment(0)
C
0

I changed all space areas to &nbsp, just like that and it worked without problem.

val.replace(" ", "&nbsp");

I hope it helps someone.

Centenary answered 25/2, 2016 at 7:13 Comment(0)
P
0

I am going to add one more answer to the pile. THis problem could happen also because of encoding. You want utf8 encoding to be on safe side. Some editors by default use utf16 which can cause issue. One quick way to test this, is, for example in VS code, simply recreate the same content but use the local editor of vscode to create the file. Hope this helps some.

Pageboy answered 28/12, 2019 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.