Why You Should be Verifying Your Javascript (JSLint)

LintIn an attempt to improve the user experience modern websites are using javascript more and more. If you are even remotely serious about performance then you need to merge your script files and minify the result. Minification is the process of removing unnecessary characters from a resource to reduce the size of the file.

You need to verify your javascript because javascript tries to tolerate errors. I'm going to go out on a limb and say that this is stupid. It can lead to a situation where invalid javascript works in its full form, but fails when minified.

Here is an example:

        function(responseText) {
            Chapter.ShowNewChapter(isForwards);
            var expr = /<div id="chapter_id" style="display: none;">(\d+)<\/div>/
            var result = expr.exec(responseText);
            if (result && result.length > 1) { Chapter.CurrentChapterId = result[1]; }
            Chapter.FetchMetadata();
        })

The third line contains a regular expression after which I have neglected to add a semicolon to terminate the line. The last line is also missing a semicolon. Unfortunately, this works fine, until the script is minified. During minification the line breaks are removed because they are unnecessary characters and the javascript interpreter can no longer determine the end of each statement.

The good news is that Douglas Crockford has provided a solution. JSLint is a javascript code verifier in the style of the lint tool for C. JSLint comes with a timely disclaimer, "Warning: JSLint will hurt your feelings". It recommends a conservative javascript style so there are typically a lot of recommendations. To use JSLint you can paste your code into a textbox at www.jslint.com and click the JSLint button. It can also be run from the command line and so included into build scripts.

The creator of JSLint, Douglas Crockford, is skilled at leading people towards a safe and efficient use of javascript. If you are working with Javascript I strongly recommend his book 'Javascript: The Good Parts'.


Comments are closed