Search code examples
javascriptecmascript-6ecmascript-5

Valid special character ↂ as variable name - error on Safari/iOS


I am using the special character ↂ as a JS variable name to namespace my framework. It should be valid according to the specs of both ES5 and ES6 (it is in the Unicode group 'Number, Letter' (http://www.fileformat.info/info/unicode/category/Nl/list.htm))

On iOS Safari however this gives the error: SyntaxError: Invalid character '\u8578'. Which seems strange because that character code appears to be a Chinese character: http://www.fileformat.info/info/unicode/char/8578/index.htm

So the code snippet below does not work on iOS Safari (Have not tested desktop Safari)

<script>
  var ↂ = 5;
  alert(ↂ);
</script>

I was trying around by setting a few values for charset="..." on the script tag but that didn't help

  1. Why does iOS Safari not accept ↂ which should be valid even in ES5?
  2. Is there a way to use ↂ without getting the error?

Please do not respond with unasked advice like 'It is bad practice to use special characters in JS'. I am aware of your opinions, please keep them to yourselves


Solution

  • I will answer my own question. Apparently not all modern browsers follow the specifications of ES5/ES6 for allowed characters. I wrote a useful code snippet that will show you which variable names work in the current browser:

    var allowed = '';
    
    function check() {
      var char = String.fromCharCode(i);
      if (char.length) {
        try {
          eval("var " + char + "=1;");
          allowed += char + ' ';
        } catch (e) {}
      }
    }
    for (var i = 0; i <= 15000; i++) {
      check(i);
    }
    document.body.innerHTML = allowed;

    Also on JSFiddle: https://jsfiddle.net/9539cc7q/

    Raise the max char code (now 15000) to your liking, the code will then run longer

    When run on Safari we can indeed see that the ↂ symbol is not allowed.