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.
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.
Share Improve this question edited Mar 11, 2013 at 7:32 MaiaVictor asked Mar 11, 2013 at 7:27 MaiaVictorMaiaVictor 53k47 gold badges157 silver badges301 bronze badges 7- 1 Javascript isn't a piled language. – Bernie Commented Mar 11, 2013 at 7:28
- the pilation of javascript is too damn high! – Henrik Andersson Commented Mar 11, 2013 at 7:29
- 1 @Dokkat, you missed a spot. – Bernie Commented Mar 11, 2013 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. – user1233508 Commented Mar 11, 2013 at 7:32 - 3 @Dokkat jslint. and jshint. – Henrik Andersson Commented Mar 11, 2013 at 7:33
2 Answers
Reset to default 16Yes, 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).
You could use esprima.
Esprima (esprima) is a high performance, standard-pliant ECMAScript parser written in ECMAScript (also popularly known as JavaScript).
Features
- Full support for ECMAScript 5.1 (ECMA-262)
- Sensible syntax tree format, patible 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 mand line. There are two mands: 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 pleteness esparse
produces an AST.