5

Is there a function to test if a snippet is valid JavaScript without actually evaluating it? That is, the equivalent of

function validate(code){
    try { eval(code); } 
    catch(err) { return false; }
    return true;
};

without side effects.

  • 1
    Javascript isn't a compiled language. – Bernie Mar 11 '13 at 7:28
  • the compilation of javascript is too damn high! – Henrik Andersson Mar 11 '13 at 7:29
  • 1
    @Dokkat, you missed a spot. – Bernie Mar 11 '13 at 7:30
  • 2
    new Function(code) will throw if there's a Syntax Error. Reference Errors cannot be detected without actually executing the code, of course. – DCoder Mar 11 '13 at 7:32
  • 3
    @Dokkat jslint.com and jshint.com – Henrik Andersson Mar 11 '13 at 7:33
12

Yes, there is.

new Function(code);

throws a SyntaxError if code isn't valid Javascript. (ECMA-262, edition 5.1, ยง15.3.2.1 guarantees that it will throw an exception if code isn't parsable).

Notice: this snippet only checks syntax validity. Code can still throw exceptions because of undefined references, for example. It is a way harder to check it: you either should evaluate code (and get all its side effects) or parse code and emulate its execution (that is write a JS virtual machine in JS).

2

You could use esprima.

Esprima (esprima.org) is a high performance, standard-compliant ECMAScript parser written in ECMAScript (also popularly known as JavaScript).

Features

  • Full support for ECMAScript 5.1 (ECMA-262)
  • Sensible syntax tree format, compatible with Mozilla Parser AST
  • Heavily tested (> 550 unit tests with solid 100% statement coverage)
  • Optional tracking of syntax node location (index-based and line-column)
  • Experimental support for ES6/Harmony (module, class, destructuring, ...)

You can use the online syntax validator or install it as npm package and run it locally from the command line. There are two commands: esparse and esvalidate. esvalidate yields (given the example from the online syntax validator above):

$ esvalidate foo.js 
foo.js:1: Illegal return statement
foo.js:7: Octal literals are not allowed in strict mode.
foo.js:10: Duplicate data property in object literal not allowed in strict mode
foo.js:10: Strict mode code may not include a with statement

For the sake of completeness esparse produces an AST.

Your Answer

By clicking โ€œPost Your Answerโ€, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.