(This is a bit of an X-Y problem, but I decided to ask the question that interests me, rather than the one I strictly need at the moment.) I know the various modern JavaScript engines have dead code eliminators and other means to get rid of code that has no effect or side effect, but how do you identify and/or compose such code?
The Wikipedia article on Dead code elimination gives one straightforward example of unreachable code, that is, code that happens after the unconditional return
statement in a function. But can I count on the modern, major JavaScript engines to eliminate such code? For example, will Rhino or V8 eliminate this code?
function (foo) {
return;
return foo;
}
function (foo) {
foo = foo;
}
and what about no op functions?
(function () {}(foo));
jQuery.noop(foo);
All of these examples fool JSHint, and while JSLint catches the weird assignment foo = foo
, you can still trick it quite easily with the noops or a pair of variables:
function (foo) {
var bar = foo;
}
If they can trick the static code analyzers, will they trick the engines themselves?
Short of closely examining the source of all the different JavaScript engines, is there any way to identify and/or construct the kind of code that will surely be eliminated before the program is ever run, and should it be considered a bug if such code is not elided, or is it merely a design choice?