What's the main benefit of using eval() in JavaScript?
The eval
function is best used: Never.
It's purpose is to evaluate a string as a Javascript expression. Example:
eval('x = 42');
It has been used a lot before, because a lot of people didn't know how to write the proper code for what they wanted to do. For example when using a dynamic name for a field:
eval('document.frm.'+frmName).value = text;
The proper way to do that would be:
document.frm[frmName].value = text;
As the eval
method executes the string as code, every time that it is used is a potential opening for someone to inject harmful code in the page. See cross-site scripting.
There are a few legitimate uses for the eval
function. It's however not likely that you will ever be in a situation where you actually will need it.
This is quite an old question, and perhaps people didn't think of use cases for eval()
properly at the time. One great use for eval()
is for implementing hot reloading into your backend or frontend development flow.
Basically eval()
can make it possible for you to edit code in your editor, and have it patch your running application without it restarting, and without it losing state (depending on the implementation). You will need associated code that watches for file changes, and somehow sends the changes to your application, but eval()
is ultimately the method of converting those changes into actual js.
EDIT
Another use case I have come across:
You can use eval()
to bypass webpack's compilation process in events where you want to dynamically require files that you don't want to be transpiled (like json) For example:
const data = eval('require')(`./emails/${recipient}/${type}.json`)
On that note, I think it is entirely wrong to write a statement like eval()
is evil, or should never be used. Blanket statements like these are the real evil!
eval
makes it possible to execute (or evaluate) a string of javascript code.
Thus, it is applicable when you want someone to execute a string of javascript code. Like, for example, under an educational article about JavaScript, so the reader can immediately try it :)
Or, again if your website is targeted to programmers, you may want them to write and execute their own plugins.