javascriptsyntaxjslintjshint

Simple way to check/validate javascript syntax


I have some big set of different javascript-snippets (several thousands), and some of them have some stupid errors in syntax (like unmatching braces/quotes, HTML inside javascript, typos in variable names).

I need a simple way to check JS syntax. I've tried JSLint but it send too many warnings about style, way of variable definitions, etc. (even if i turn off all flags). I don't need to find out style problems, or improve javascript quality, i just need to find obvious syntax errors. Of course i can simply check it in browser/browser console, but i need to do it automatically as the number of that snippets is big.

Add:
JSLint/JSHint reports a lot of problems in the lines that are not 'beauty' but working (i.e. have some potential problems), and can't see the real problems, where the normal compiler will simply report syntax error and stop execution. For example, try to JSLint that code, which has syntax errors on line 4 (unmatched quotes), line 6 (comma required), and line 9 (unexpected <script>).

document.write('something');
a = 0;
if (window.location == 'http://google.com')  a = 1;
document.write("aaa='andh"+a+"eded"');
a = {
  something: ['a']
  something2: ['a']
};
<script>
a = 1;

Solution

  • I've found that SpiderMonkey has ability to compile script without executing it, and if compilation failed - it prints error.

    So i just created small wrapper for SpiderMonkey

    sub checkjs {
        my $js = shift;
        my ( $js_fh, $js_tmpfile ) = File::Temp::tempfile( 'XXXXXXXXXXXX', EXLOCK => 0, UNLINK => 1, TMPDIR => 1 );
        $| = 1;
        print $js_fh $js;
        close $js_fh;
        return qx(js -C -f $js_tmpfile 2>&1);
    }
    

    And javascriptlint.com also deals very good in my case. (Thanks to @rajeshkakawat).