JSLint Messages – document.write can be a form of eval.

JSLint flags any use of the eval statement with the message eval is evil. This is because eval is a hook right into the JavaScript compiler. It accepts a string as a parameter and then compiles it and runs it.

Further resources on the evils of eval are available through the above link. Here we are more interested in how document.write can equate to eval

So how can document.write possibly equate to being the same? Well, we can demonstrate this with a simple example. You’ll need to set up an HTML page and a JS File with the following code:

HTML File

<script src="a.js" type="text/javascript"></script>

JS File

document.write('<script type="text/javascript">alert(1 + 2);</script>');
alert(eval(1+2));

Or alternatively, download them from my sample: document.write.eval.zip

What happens when you run it? Well, you get “3” output twice.

The JavaScript compiler picks up the first line, and writes out some more JavaScript, which itself has to be executed and fed back into a compiler. So, in effect, we have a line of JavaScript that is responsible for invoking the compiler again. This first line is sending 1+2 to the compiler to be evaluated.

This is pretty much identical to what is happening with eval(1+2) in our second line.

Of course, the above works because we have separated out our HTML and JS. What if we had it all in a single HTML page. Something like

<script src="a.js" type="text/javascript">
   document.write('<script type="text/javascript">alert(1 + 2);</script>');
</script>

When document.write outputs , it closes the original script tag on the first line. We are then left with a hanging ‘); that is output to the browser and an orphaned closing script tag.

This may not be eval, but it is certainly evil.

So, there we have it document.write can be a form of eval. But it doesn’t have to be eval to be evil. It should, therefore, be avoided.

We can, of course, turn this up simply by turning on the ‘evil’ JSLint option, like so:

/*jslint evil: true */

Thanks to the wisdom of StackOverflow for helping answering this: JSLint “document.write can be a form of eval” – How is this so?

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

3 thoughts on “JSLint Messages – document.write can be a form of eval.

  1. Pingback: James Wiseman » Material from Techmeetup Talk

  2. Pingback: JSLint – A Guide To JSLint Messages | James Wiseman

  3. Pingback: Eval is Evil | James Wiseman

Leave a Reply