W3C.US

  • Increase font size
  • Default font size
  • Decrease font size
Home Experience Javascript Javascript:eval==evil?

Javascript:eval==evil?

E-mail Print PDF

In javascript, the eval function is a powerful and easy way to dynamically generate code. But it'll taken some problems to your webpage:

  • Improper use of eval opens up your code for injection attacks
  •  
  • Debugging can be more challenging (no line numbers, etc.)
  •  
  • eval'd code executes more slowly (no opportunity to compile/cache eval'd code)

And eval function is not always evil like above:



However, eval is currently and historically massively over-used by people who don't know what they're doing. That includes people writing JavaScript tutorials, unfortunately, and in some cases this can indeed have security consequences - or, more often, simple bugs. So the more we can do to throw a question mark over eval, the better. Any time you use eval you need to sanity-check what you're doing, because chances are you could be doing it a better, safer, cleaner way.

To give an all-too-typical example, to set the colour of an element with an id stored in the variable 'potato':
eval('document.'+potato+'.style.color= "red"');

If the authors of the kind of code above had a clue about the basics of how JavaScript objects work, they'd have realised that square brackets can be used instead of literal dot-names, obviating the need for eval:
document[potato].style.color= 'red';

...which is much easier to read as well as less potentially buggy.

(But then, someone who /really/ knew what they were doing would say:
document.getElementById(potato).style.color= 'red';

which is more reliable than the dodgy old trick of accessing DOM elements straight out of the document object.)