52

I know this may be a newbie question, but I'm curious as to the main benefit of eval() - where would it be used best? I appreciate any info.

Caffeinated
  • 11,982
  • 40
  • 122
  • 216
  • 4
    possible duplicate of [Is there ever a good reason to use eval()?](http://stackoverflow.com/questions/1826859/is-there-ever-a-good-reason-to-use-eval) – Felix Kling May 06 '12 at 21:07
  • 2
    Why is this tagged `homework `? – Derek 朕會功夫 May 06 '12 at 21:28
  • 1
    @Adel, I know it is a bit too late, but I just found a PERFECT way of using `eval`...: http://stackoverflow.com/a/10508240/283863 – Derek 朕會功夫 May 09 '12 at 00:16
  • 1
    Eval can help you with performance in certain scenario. I am not sure how the browser was in 2012 but today a browser console can be the best vulnerable place to hack your data. – Venkatesh Nadar Oct 05 '15 at 10:37
  • Just wanted to add this. If you have decided to use eval then read this. Eval has some security concerns and there are ways to overcome that, one way is using safe-eval, but it comes with added performance overheads. You can read about how eval is vulnerable and it's performance comparison with safe-eval, with examples and stats here https://ayushchaurasia96.medium.com/safe-eval-and-eval-whats-the-fuss-aa495c4eaa96 – Ayush Chaurasia Dec 28 '20 at 11:55

15 Answers15

46

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • I have a sample code block on a webpage that users will be able to run. Would this be a case where eval should be used or is there a better option? – sdfsdf Jul 29 '18 at 18:42
  • 1
    You do not `eval()` to orchestrate an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting). So, avoiding use of `eval()` makes code no more secure than using it. It is about validating (filtering) user input, it is not about `eval()`, `alert()`, `javascript:`, etc.. – Elis Byberi Sep 02 '18 at 11:20
  • I disagree, there are some situations, for instance if you have an ASP.Net server side LinkButton with `hfref` attribute like this: `href="javascript:__doPostBack('sfw$fc$fccd$e8$dui10$btnLinkUse','')"`and you need to trigger click by code you can't use `$("#").click()` or even `$("#").trigger("click")`, you have to use `eval($("#").attr("href"))`. – Muhammad Musavi May 05 '19 at 06:09
  • Sometimes you need eval function where no other solutions work. So it is not proper to say 'never' for usage of eval function. It is important to know how to keep the knife. – yılmaz Jun 12 '19 at 08:27
45

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!

Matt Way
  • 32,319
  • 10
  • 79
  • 85
  • 3
    This is the best and real use case I came across. (y) – Ravi Roshan Aug 25 '17 at 12:47
  • 1
    Neat answer. If someone was building something like ReactJS or Angular or NodeJS, this answer would be useful. =) – HoldOffHunger Nov 16 '17 at 14:56
  • 2
    Of all the answers this is the only one with actual content. **There are valid use cases,** Which ones?. **Don't use it, ever!** Why `eval` exists then? Great answer! – Dupocas Dec 10 '19 at 14:32
  • 1
    Oof thank you so much, I was having trouble with an `eval` and `require` combo but this setup helped me out. – rmolinamir Apr 29 '20 at 19:53
11

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.

Imp
  • 8,409
  • 1
  • 25
  • 36
8

The best goal of using eval is to dynamically load code, generate code at runtime and do similar meta programming stuff. In general, if you can do the same without eval, don't use eval.

Konstantin Solomatov
  • 10,252
  • 8
  • 58
  • 88
6

eval() should not be used in Javascript.

eval() used to be used to parse JSON strings, but that use has been superseded by the faster and more-secure JSON.parse.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Ah, I see - so it is a risky function - I will read more. Thank You, – Caffeinated May 06 '12 at 21:08
  • 3
    @Guffa: Yes, but it shouldn't have been. – SLaks May 06 '12 at 23:13
  • The JSON parsing function is [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). – Sumit Dec 04 '18 at 11:48
  • "eval() should not be used in Javascript.". I disagree. It should be used with care. If it shouldn't be used then it shouldn't be part of the language – Peter Chaula Mar 14 '19 at 11:48
  • @peter: There are many things in JavaScript that should not have been part of the language (most notably, `with()`). – SLaks Mar 14 '19 at 15:16
3

You can run JS that is stored in the value of a field on the webpage.

You can use eval with JS, it's just that then your code is more viable to attack. As long as it doesn't use AJAX, there's no server problem.

If you use eval, you should parse out the characters [ ()<>{} ]

PitaJ
  • 12,969
  • 6
  • 36
  • 55
2

                  eval() = evil

You should not really use it at all. It can be used for easy code insert, but someone can insert bad scripts using eval(). Sometimes people use eval() for parsing JSON, or

eval("obj." + id);   //newbies

but actually you can achieve all those things without using eval().

obj[id];             //should-do
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • We all know that you shouldn't use `eval`; the OP was asking if there were any benefits. – Jeffrey Sweeney May 06 '12 at 21:11
  • @JeffreySweeney - (there isn't any of them I can think of...) – Derek 朕會功夫 May 06 '12 at 21:12
  • I know right? :P Perhaps it could be used for testing back-end vulnerability on a test server, or for speed testing (since it's one of the slowest functions in JS). – Jeffrey Sweeney May 06 '12 at 21:14
  • 2
    And did you really think? I'm often feeling some kind of bigotry from the programming community. If there is something that is mostly bad and is being discouraged by authoritative articles, people stop using it even in those few cases where it's actually applicable and good. – Imp May 06 '12 at 21:15
  • @Imp It can be easy and convenient to execute codes, but it also let some bad users to insert malicious scripts. (according to Google) – Derek 朕會功夫 May 06 '12 at 21:17
  • @Derek Of course, I understand. But sometimes you have no backend you could expose and endanger, so there is no real security problem. And to some problems, `eval()` is a solution with the same security risks as other solutions. You can't immediately say that something *never* has usage only because it *mostly* doesn't. – Imp May 06 '12 at 21:23
1

Maybe I am wrong, but I am using it to parse a string from a templete file:

const name = 'Daman'
const fileContent = 'Hello ${name}'
const result = eval('`' + fileContent + '`')

Which gives me just what I need:

"Hello Daman"
Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
0

one of the best use case using eval is javascript logger in which user can execute javascript in run time. for example javascript logger allowing the user to execute script in logger window.

0

As said earlier, there is a potential risk involved while using eval(), If you want to evaluate string as expression you can use ${} to evalute expression, introduced in ECMA-6

Swesh
  • 150
  • 1
  • 17
0

To dynamically run code based on strings that represent javascript code. e.g:

let dynamicFunc = eval('(x)=>(x+2)') // or whatever plain text which is valid JS function
console.log(dynamicFunc(40));
// expected output: 42

Security warning! you should always validate these strings to avoid malicious scripts execution, especially when using it on the server side.

ykorach
  • 588
  • 6
  • 14
-1

you could build a client skeleton and have it work as a foundation app - receiving bundles of code and then executing them - thereby making the client extremely flexible -- having all code on server in bundles. This however is highly risky and if such a thing is needed, then you should perhaps use Java with Java bundles. Why Eval is still in the language is debateable, it is a too big security risk to use

serup
  • 527
  • 5
  • 11
-1

Using eval is usefull, but like everything else, you must be aware of the risks. Every pice of JS code is a potential risk. Bugs in software creep in through logical errors and coding errors witht unintended consequences. I always say that computers never do what you want them to do, they do what you tell them to do. That means you must remember that software has to be carefully thought out. Software hasn't changed. People still code on-the-fly instead of careful analasys and proper design. We are all guilty of the same sins in software development. Use eval - eval is not evil, it is what you make it.

Raoul
  • 1
  • 1
-1

Never say never. Eval has very good legitimate use cases. It's just a powerful tool, so if you aren't conscientious of how you're using it you could create a serious problem.

Since Javascript is executed client side, the security risk is to the client rather than the server. If you use eval in javascript and you aren't careful to validate the source of input or the content of that input to the eval function, you'd be responsible for potentially serious consequences for the client.

Having said that, the best use I've made of javascript eval is when writing various types of parsing routines. It's often handy to put simple (or sometimes not-so-simple) math formulas into data as a string that's stored in a database for example. If your program needs to perform arbitrary calculations on variables that are otherwise controlled by the program, eval is the best way to do that. It can be unnecessarily complex manually parse a securely managed string.

As developers we can't fully control what happens client side. A user can always muck about in the console and create their own problems, or download browser extensions that interfere with JS execution. The best we can do is to limit risk exposure, and not be so negligent as to leave gaping security holes.

J.Raney
  • 11
  • 3
-2

Eval() can be very useful, even though it was said to be "undone". I use it in autoit to enable code upon code.

It can be applied when writing a code-processor to create your own script.

WHY? In my case using this on a large scale tcp server doesn't require me to recompile source code and kick all clients cause of restarting. So I use eval to add in new scripts on the fly unlike a config stuff it isn't static and can be used to calculate etc. Also combining eval with call commands can set a value by eval from a function.

But beside that, it won't be much safe to use. Even using it this way I recommend making it fail safe for sure.

double-beep
  • 5,031
  • 17
  • 33
  • 41