Search code examples
javascriptcommentscharacterspecial-characters

Special characters in JavaScript comments


I want to embed a cheat code into the comments of a JavaScript file. It's an Easter egg if people view the source. Will these special characters (the arrows) be a problem for JavaScript interpreters?

/*
 ( " ↑ ↑ ↓ ↓ ← → ← → B A ENTER " )
*/

Solution

  • It’s safe. Within a comment, any characters can be used, except those recognized as terminating a comment by the language specification. By the ECMAScript standard, a comment may contain any Unicode code unit, and there is no reason to suspect that implementations fail to obey this (they just need to skip all character data there, recognizing only comment termination).

    However, a user viewing a .js file may or may not see the characters correctly, depending on the character encoding settings. You cannot guarantee this, but you can help with it by serving .js files from the server with Content-Type: text/javascript; charset=utf-8 (if your file is UTF-8 encoded, as it most probably is in this case) and by using the attribute charset=utf-8 in the script element that refers to the file. Oh, and use UTF-8 with BOM.

    Even if the encoding issue is handled properly, there is the possibility that the program used for viewing the .js file uses a font that does not contain the character you have in the comment, so they won’t be seen by the peeking visitor. But this does not affect functionality.