Why does YUI Minify fail on char and browsers do not in JavaScript

This weeks 30 second question. Why does YUI Minify fail on char and browsers do not in JavaScript?

In JavaScript the following line of code works on all browsers that I have seen:

var char = 15;

However, the YUI minifier chokes on this line of code. Why is this? And should that line not work on browsers? i.e. why are browsers allowing that line to work?

Let’s start out with Reserved words in Javascript.  These words are words that you cannot use as variable or function names as they hold special meanings and instruction to the language.  If you haven’t guess by now, ‘char’ is a reserved keyword in JavaScript.  So in the above example we are trying to use a keyword as a variable name which causes the YUI Minify to throw a fit.  To give you an example, open up this link and plug in the following and click compress.

http://www.refresh-sf.com/yui/

var char = 15

You will be prompted with the error below.

[ERROR] 1:10:missing variable name

[ERROR] 1:0:Compilation produced 1 syntax errors.

org.mozilla.javascript.EvaluatorException: Compilation produced 1 syntax errors.
	at com.yahoo.platform.yui.compressor.YUICompressor$1.runtimeError(YUICompressor.java:154)
	at org.mozilla.javascript.Parser.parse(Parser.java:392)
	at org.mozilla.javascript.Parser.parse(Parser.java:337)
	at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:312)
	at com.yahoo.platform.yui.compressor.JavaScriptCompressor.<init>(JavaScriptCompressor.java:533)
	at com.yahoo.platform.yui.compressor.YUICompressor.main(YUICompressor.java:131)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:585)
	at com.yahoo.platform.yui.compressor.Bootstrap.main(Bootstrap.java:21)

That answers the first part of the question, now onto the second part of the question.  Why do browsers still allow this code snippet to work?  Well, the keyword char is not actually used by the JavaScript language.  So yes it’s labeled as a reserved keyword, but it is never been used as one. Browsers run their own compilers for JavaScript and tend to have more of a lenient stance on this subject.  They want to allow as much of the JavaScript execute as they possibly can.  So since there is not a repercussion of using this keyword, the browsers don’t take it into account as an issue.  The YUI Minify is a more standards compliant engine that will follow standards, hence why it blows up when you try to use a keyword it recognizes as a word that’s off limits.


One thought on “Why does YUI Minify fail on char and browsers do not in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile