The many lives of JavaScript variables
So, It was about three months ago when I first met jQuery. It’s a neat little library that helps JavaScript programmers easily do relatively complex things. Among many of its features one stood out to me. The $() function is an interesting beast that takes a CSS selector or XPath and returns a set of matching nodes. However, the application of it was not what attracted me to it.
The Revelation
The name, a single dollar sign, is what struck me. I never knew that such a character could be used in a variable name. As I, and many others, were taught the only character allowed were:
- letters
- underscores
- and numbers so long they are not the first character
I was interested and decided to embark on quest to figure out what characters were allowed and which weren’t. This took me to the ECMA-262 specification, the standard for JavaScript, or ECMA Script as its formally called. The standard states:
Identifiers are interpreted according to the grammar given in Section 5.16 of the upcoming version 3.0 of the Unicode standard, with some small modifications.
The Unicode Standard allows for nearly 14,000 characters to be used in variables, as opposed to the measly 63 that are commonly used.
The Disappointment
I instantly tried to stuff Sigmas (Σ) and Double Struck N’s (ℕ) in to my code, but to my dismay, they didn’t work. Disappointing? Yes. Surprising? No. It seems to be this way with all web standard’s, either implemented wrongly or incompletely (or both, heres looking at you Microsoft). So, to test compliance I wrote a small JavaScript that creates a variable, using one of the Unicode characters, and assigns a value to it. If throws an exception, then that means the browser doesn’t support that character. Simple enough, but who wins this browser compliance battle. So far Opera, it supports 99.5% of all characters. Heres the data I’ve collected so far:
| Browser | Chars Tested | Non Supported Chars | % Not Supported |
| Opera 9.27 (Ubuntu Linux) |
13935 | 78 | 0.5597416576964478 |
| Opera 9.63 (Windows XP & Ubuntu Linux) |
13935 | 80 | 0.5740940078937926 |
| Internet Explorer 8 beta (Windows 7 beta) |
13935 | 2131 | 15.292429135270902 |
| Google Chrome (Windows XP) |
13935 | 2746 | 19.705776820954434 |
| Internet Explorer 7 & 6 (Windows XP) |
13935 | 4340 | 31.144599928238246 |
| Firefox 3.0.X (Windows XP & Ubuntu Linux) |
13935 | 7220 | 51.811984212414785 |
Yeah, I know thats a pathetically small dataset, but you can help run the test script and then post the last three lines in the comments along with the browser, version, and OS. WARNING: This script takes a very long time to execute, it may appear to lock your browser up, but be patient.
On an unrelated note, Chrome’s Javascript engine was suprisingly fast.
Tags: javascript, special characters, variables
