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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With