Got a Parser error in OSX Safari today that didn’t appear in Chrome. On the surface it appears as if its just a silly mistake that I overlooked – another developer used the “default” keyword in his XML, which I converted to JSON and used in my app which appeared similar to this:
... var something = [{default:'abc'}]; var cat = something[0].default; ...
Chrome on Windows and OSX were fine yet Safari on OSX tripped on it. The answer is rather obvious – the word “default” is a reserved keyword and as such should be avoided. As a quick reference the rest of the keywords are:
break case, catch, continue, debugger, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, with
The fix is simple, just treat the object as an associative array and use “default” as the key to get the desired value, like so:
... var something = [{default:'abc'}]; var cat = something['default']; ...
Simple – and legal and in fact the first example is as well. While it is poor form to use a reserved keyword in the first example it is entirely legal to do so in that manner. The keyword exclusion only refers to using the keywords as identifiers which is not the case here. For reference see ECMAScript 5.1 here.
An example of using a keyword as an identifier (and thus something to be avoided) would be:
... function default(){ // wrong! } ...
It appears that Apple has taken things a bit too far as they often do. See this list of browsers that correctly parse the sample JS with no issues:
Browsers that Accepted the first example:
- Windows
- Safari 5.1.1
- FireFox 17.0.1
- Chrome 23.0.1271.97
- IE 9
- OSX
- Chrome 10.0.648.151
Browsers that didn’t:
- OSX Safari 5.0.5
So… there it is. Just a quirk of Safari’s JS parser to be aware of. Its yet another example of the “Great Apple Irony” – their supposed adherence to standards. I suppose they are saving us from ourselves in a way as we as developers should know better but its still goes against the grain, so-to-speak.