Why is using the JavaScript eval function a bad idea?

0 votes
asked Sep 17, 2008 by brian-singh

The eval function is a powerful and easy way to dynamically generate code, so what are the caveats?

24 Answers

0 votes
answered Jan 17, 2008 by john-topley

Unless you are 100% sure that the code being evaluated is from a trusted source (usually your own application) then it's a surefire way of exposing your system to a cross-site scripting attack.

0 votes
answered Jan 17, 2008 by matthew-crumley

Besides the possible security issues if you are executing user-submitted code, most of the time there's a better way that doesn't involve re-parsing the code every time it's executed. Anonymous functions or object properties can replace most uses of eval and are much safer and faster.

0 votes
answered Jan 17, 2008 by brian

This may become more of an issue as the next generation of browsers come out with some flavor of a JavaScript compiler. Code executed via Eval may not perform as well as the rest of your JavaScript against these newer browsers. Someone should do some profiling.

0 votes
answered Jan 17, 2008 by thevs

Unless you let eval() a dynamic content (through cgi or input), it is as safe and solid as all other JavaScript in your page.

0 votes
answered Jan 17, 2008 by tom

It is a possible security risk, it has a different scope of execution, and is quite inefficient, as it creates an entirely new scripting environment for the execution of the code. See here for some more info: eval.

It is quite useful, though, and used with moderation can add a lot of good functionality.

0 votes
answered Jan 17, 2008 by david-plumpton

It greatly reduces your level of confidence about security.

0 votes
answered Jan 17, 2008 by markr

It's not necessarily that bad provided you know what context you're using it in.

If your application is using eval() to create an object from some JSON which has come back from an XMLHttpRequest to your own site, created by your trusted server-side code, it's probably not a problem.

Untrusted client-side JavaScript code can't do that much anyway. Provided the thing you're eval'ing has come from a reasonable source, you're fine.

0 votes
answered Sep 17, 2008 by kevin

I believe it's because it can execute any JavaScript function from a string. Using it makes it easier for people to inject rogue code into the application.

0 votes
answered Sep 17, 2008 by brian

Mainly, it's a lot harder to maintain and debug. It's like a goto. You can use it, but it makes it harder to find problems and harder on the people who may need to make changes later.

0 votes
answered Sep 17, 2008 by mark-biek

It's generally only an issue if you're passing eval user input.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter