Checking if code is valid JavaScript without actually evaluating it

compilation, eval, javascript

Solution

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).

Problem

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.

Original source