The eval function is a powerful and easy way to dynamically generate code, so what are the caveats?
-
100Don't be eval() by Simon Willison - http://24ways.org/2005/dont-be-eval – Brian Singh Sep 17 '08 at 19:40
-
6As outlined in http://moduscreate.com/javascript-performance-tips-tricks/ - (new Function(str))() is more performant than eval(str). Just my 2 cents :) – Grgur Aug 02 '12 at 15:05
-
3apparently new fcuntion(a) is 67% slower than eval(a) on chrome – what is sleep Dec 10 '13 at 20:35
-
for me new functions(a) is 80% slower latest chrome on osx – john Smith Jan 26 '14 at 10:35
-
3I added a static function, just to compare the performance. http://jsperf.com/eval-vs-new-function/2 – Nepoxx Aug 28 '14 at 17:06
-
same caveats as include and require in PHP. eval may as well be called "include_from_string" or "runtime_compile". Not only is it not evil, but I am certain it is one of the fundamental reasons why scripting was created - it's much easier to make a script that evals' to an object and start using it/change it without recompiling than recompiling a DLL every time you need a change. From a high level viewpoint, Eval is the same as compiling a c file to a DLL, then calling its' entry point, and linking to its' state symbol(or have the entry point return the state object). – Dmytro Jun 02 '18 at 20:54
-
1@Nepoxx Your site's down – 9pfs Mar 20 '22 at 04:40
25 Answers
Improper use of eval opens up your code for injection attacks
Debugging can be more challenging (no line numbers, etc.)
eval'd code executes slower (no opportunity to compile/cache eval'd code)
Edit: As @Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval'd repeated with no modification. A more likely scenario is that you are eval'ing scripts that have undergone slight modification each time and as such could not be cached. Let's just say that SOME eval'd code executes more slowly.

- 83,552
- 10
- 84
- 84
-
3@JeffWalden, great comment. I've updated my post although I realize it has been a year since you posted. Xnzo72, if you had qualified your comment somewhat (as Jeff did) then I might be able to agree with you. Jeff pointed out the key: "eval of the same string multiple times can avoid parse overhead". As it is, you are just wrong; #3 holds true for many scenarios. – Prestaul Feb 13 '12 at 17:44
-
7@Prestaul: Since the supposed attacker can just use whatever developer tool to change the JavaScript in the client, why do you say Eval() opens up your code to injection attacks? Isn't already opened? (I'm talking about client JavaScript of course) – Eduardo Molteni Oct 24 '12 at 01:52
-
71@EduardoMolteni, we don't care (and indeed cannot prevent) users from executing js in their own browsers. The attacks we are trying to avoid are when user provided values get saved, then later placed into javascript and eval'd. For example, I might set my username to: `badHackerGuy'); doMaliciousThings();` and if you take my username, concat it into some script and eval it in other people's browsers then I can run any javascript I want on their machines (e.g. force them to +1 my posts, post their data to my server, etc.) – Prestaul Oct 25 '12 at 18:12
-
1AFAIK, google-chrome & chromium dev tools makes debugging eval'ed code just like debugging other js files. but you cannot put breakpoints though. – Mar 08 '13 at 20:38
-
3In general, #1 is true for quite a lot, if not most function calls. eval() shouldn't be singled out and avoided by experienced programmers, just because inexperienced programmers abuse it. However, experienced programmers often have a better architecture in their code, and eval() will rarely be required or even thought about due to this better architecture. – frodeborli Mar 12 '14 at 08:35
-
2@frodeborli, I disagree with your opening statement. `eval` is fundamentally different from a function call. Read my comment to EduardoMolteni (2 above yours) for an explanation. Injection attacks specifically refer to taking user input and allowing it to execute somewhere other than their own browser. (e.g. the server or another user's browser) I do, however, agree that `eval` is rarely required if you architect your applications well. It should be avoided because there is almost always a better and more secure solution. – Prestaul Mar 14 '14 at 15:28
-
4@TamilVendhan Sure you can put breakpoints. You can access the virtual file created by Chrome for your evaled coded by adding the `debugger;` statement to your source code. This will stop the execution of your program on that line. Then after that you can add debug breakpoints like it was just another JS file. – Sid Jul 25 '14 at 22:27
-
Thank you. This concise answer just told be exactly my I can use eval in my current task/context. There is so much unclear advice to just not use it. – ProfK Jun 04 '15 at 13:48
-
@frodeborli Your second statement is also wrong. Many experienced programmers / frameworks still use `evil()` a lot. Take a look at SAP OpenUI5 for example. – André Fiedler Jun 10 '15 at 16:27
-
@ProfK Think well before using `eval()`! There are more strict CSP out there preventing you from using `eval()`. Take Firefox OS for example. – André Fiedler Jun 10 '15 at 16:30
-
@AndreFiedler Neither of my statements are wrong. You might disagree, if you wish. Any functionality can be implemented in any Turing complete language. Only a few languages have eval, thus eval is never NEEDED - it is just a convenience. Whether or not eval is a function call or a language construct is a completely different question. – frodeborli Jun 11 '15 at 18:24
-
@frodeborli yeah, it's never NEEDED, but my statement was about `experienced programmers often have a better architecture in their code`. Not so often as you thought. ;) – André Fiedler Jun 12 '15 at 06:49
-
@AndreFiedler Experienced programmers may have poor code. That we can agree on. :) But a group of experienced programmers usually have a better architecture than they used to have when they were inexperienced, is what I meant to say. – frodeborli Jun 13 '15 at 15:29
-
-
`eval` isn't all that bad. I use it in my [`Epic Random String Generator`](http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript/35302975#35302975) and it works great! – SpYk3HH Apr 09 '16 at 03:38
-
If you're executing different code each time, compiling and caching would have no benefit, regardless of whether that you're using `eval` or not. – Kevin May 27 '16 at 17:43
-
(1) how is this any different from require/include? If you need to include foreign code/user code why is this even an issue? (2) modern javascript engines can tell you the exact line and offset of errors inside evaluated code as if you ran that code from anonymousScope.js. (3) how is this any different from any kind of compilation process? i'd argue that conditionally generating a function with eval is often faster than writing a function with conditions in it, or using global variables(eg manual inlining), when those generated functions are called many times. – Dmytro Jun 02 '18 at 20:43
-
@Dmitry, I'll just address 1 & 2: The big difference is that, if you are using eval, you are programmatically generating code and the most common reason people do this is to inject user-supplied information (or code) into code. This is fundamentally unsafe as it needlessly opens your code up to injection attacks. If you are using code generation for optimizations then maybe there is a legitimate use, but this is certainly a minority use case. – Prestaul Jun 04 '18 at 16:22
-
most common use of eval is to implement "require" functionality without inventing a new parser. Also I'm not sure you know what injection attacks are, but on the client side you can't avoid injection other than by function locals, and iife locals can't be touched by anything but a memory editor. On the server side, you need to be careful who you let execute arbitrary code, but even there its still used for implementing require and as a shell alternative. – Dmytro Jun 04 '18 at 17:46
-
@Dmitry, I think you fundamentally misunderstand injection attacks... There is no threat from injection done on the client side by a user viewing their own content. We're concerned about XSS which has to do with injection of malicious content from ANOTHER user, giving them access to a page in which a different user is logged in. There are ways to avoid this but if you use eval it depends entirely on the knowledge and diligence of the developers. If you want require, just use a lib that does it right. See: https://codereview.stackexchange.com/questions/25901/javascript-modules-loading-with-eval – Prestaul Jun 05 '18 at 20:09
-
@Prestaul eval in xss is dangerous but can be mitigated by hiding important data in local variables inside functions, and credential testing before eval of text loaded from foreign domains. eg instead of eval of code you could json parse the request to eval and check the objects credentials before eval of its code property. that said, i can't imagine a need to eval of xss. – Dmytro Jun 05 '18 at 23:27
eval isn't always evil. There are times where it's perfectly appropriate.
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.)
-
87Hmm, guess I got lucky when I was first learning JavaScript. I always used "document.getElementById" to access the DOM; ironically, I only did it at the time because I didn't have a clue how objects worked in JavaScript ;-) – Mike Spross Mar 15 '09 at 06:45
-
5
-
45@schoetbi: Shouldn't you use `JSON.parse()` instead of `eval()` for JSON? – alexia Jan 10 '11 at 21:46
-
1@Nyuszika7H: when you can, sure. There are still a fair few extant browsers that don't have it, alas. – bobince Jan 11 '11 at 00:53
-
4@bobince http://code.google.com/p/json-sans-eval/ works on all browsers, so does https://github.com/douglascrockford/JSON-js . Doug Crockford's json2.js does use eval internally, but with checks. Besides, it's forward-compatible with built-in browser support for JSON. – Martijn Feb 01 '11 at 10:13
-
2Sure, you can use libraries if you like. But all browsers are going to have to download the library code, even if they have native support so will never use it. For cases where I'm sure the JSON is going to be safe, and valid as a JS literal as well as JSON, I'd much rather save the extra bulk and plump for `eval`. – bobince Feb 05 '11 at 11:38
-
9@bobince There is something called feature-detection and polyfills to handle missing JSON libraries and other things (look at http://modernizr.com/) – MauganRa Nov 22 '12 at 16:04
-
1"eval isn't always evil." Isn't it? I don't know of any case where `eval` is the best option. FWIW you can achieve much of the same functionality using the `Function` constructor ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function ), which is slightly less evil. – David Knipe Jun 07 '19 at 20:25
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.

- 30,738
- 21
- 105
- 131

- 113,795
- 27
- 197
- 251
-
7
-
5Really the alternative is just write code that doesn't require it. Crockford goes into length about this, and if you need to use it, he pretty much says that its a program design flaw and needs to be reworked. In truth, I agree with him too. JS for all it's flaws is really flexible, and allows a lot of room to make it flexible. – kemiller2002 May 12 '14 at 14:46
-
but when you get a response from the server by AJAX, you will get response text xmlHttp.responseText, and you will need to use eval to execute it. – moderns May 12 '14 at 14:47
-
3Not true, most frameworks have a method to parse JSON, and if you aren't using a framework, you can use JSON.parse (). Most browsers support it, and if you're really in a pinch, you could write a parser for JSON pretty easily. – kemiller2002 May 12 '14 at 14:58
-
6I don't buy this argument, because it already is easy to inject rogue code into a Javascript application. We have browser consoles, script extensions, etc... Every single piece of code sent to the client is optional for the client to execute. – user2867288 Feb 04 '15 at 14:37
-
7The point is that's it's easier for me to inject code into your browser. Let's say you're using eval on a query string. If I trick you into clicking a link that goes to that site with my query string attached, I've now executed my code on your machine with full permission from the browser. I want to key log everything you type on that site and send it to me? Done and no way to stop me because when eval executes, the browser gives it highest authority. – kemiller2002 Feb 04 '15 at 15:00
-
I use it for dynamic formula processing where the formula is sent from a server. There is no security risk here and the only alternative would be to write a big JavaScript function to deconstruct the formulas. – nuander Sep 15 '15 at 23:08
-
@Kevin Then how do you feature-detect for ECMAScript 6 (ES6) support without `eval`? Or does Crockford recommend just shunning ES6 entirely? – Damian Yerrick Mar 18 '16 at 04:42
-
@nuander Then serve the big function as a separate .js file and include it by appending a script element to the document. – Damian Yerrick Mar 18 '16 at 04:43
-
1@DamianYerrick It's impossible in some feature detection to not use it. At that point I would question if ES6 was really worth implementing in that scenario. If you have to do feature detection to see if you can use it, that means you have to account for the scenarios where you can't. This really means that you have to write your code twice (once in ES5 and once in ES6). I'd just stay with ES5, or write the code in TypeScript etc so I can transpile to ES6 when I don't have to support 5 anymore. – kemiller2002 Mar 18 '16 at 13:34
-
3Why would anyone eval a query string? Nowadays you don't even need to POST, let alone GET, because there are websockets. And you can always sandbox an iframe, or use a web worker, where there are only 'messages' communicated between the two and have no acess to each other's namespace. – jdmayfield Feb 08 '18 at 05:20
It's generally only an issue if you're passing eval user input.

- 146,731
- 54
- 156
- 201
-
1This means just some simple on page calculations will not harm anything. Good to know that. – Sohan Arafat Sep 19 '21 at 00:03
Two points come to mind:
Security (but as long as you generate the string to be evaluated yourself, this might be a non-issue)
Performance: until the code to be executed is unknown, it cannot be optimized. (about javascript and performance, certainly Steve Yegge's presentation)

- 40,723
- 12
- 105
- 192
-
10Why security is an issue if client anyway could do with our code anything he/she wants ? Greasemonkey ? – Paweł Brewczynski Mar 10 '13 at 16:01
-
5@PaulBrewczynski, the security problem appears when user A saves his part of code to be `eval`uated and then, that little piece of code runs on user's B browser – Felipe Pereira Dec 03 '14 at 14:33
Passing user input to eval() is a security risk, but also each invocation of eval() creates a new instance of the JavaScript interpreter. This can be a resource hog.

- 21,688
- 16
- 67
- 79
-
31In the 3+ years since I answered this, my understanding of what happens has, let's say, deepened. What actually happens is a new execution context is created. See http://dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts/ – Andrew Hedges Jan 26 '12 at 03:46
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.

- 30,738
- 21
- 105
- 131

- 4,931
- 3
- 32
- 55
-
Eval can be used to substitute missing metaprogramming features, like templates. I like compact generator way more than endless list of functions upon functions. – weaknespase Nov 10 '16 at 17:47
-
As long as the string doesn't come from the user, or is limited to the browser you can. JavaScript has lots of metaprogramming power using stuff like changing prototypes, obj[member], Proxy, json.parse, window, decorator functions(adverbs) where newf = decorator(oldf), higher order function like Array.prototype.map(f), passing arguments to other functions, keyword arguments via {}. Can you tell me a use case where you can't do these instead of eval? – aoeu256 Jul 19 '19 at 15:51
One thing to keep in mind is that you can often use eval() to execute code in an otherwise restricted environment - social networking sites that block specific JavaScript functions can sometimes be fooled by breaking them up in an eval block -
eval('al' + 'er' + 't(\'' + 'hi there!' + '\')');
So if you're looking to run some JavaScript code where it might not otherwise be allowed (Myspace, I'm looking at you...) then eval() can be a useful trick.
However, for all the reasons mentioned above, you shouldn't use it for your own code, where you have complete control - it's just not necessary, and better-off relegated to the 'tricky JavaScript hacks' shelf.

- 14,451
- 16
- 82
- 145

- 2,174
- 3
- 28
- 47
-
1Just updating the above code.. --hi there!-- needs to be in quotes as it is a string. eval('al' + 'er' + 't(' + '"hi there!"' + ')'); – Mahesh May 20 '14 at 05:23
-
3`[]["con"+"struc"+"tor"]["con"+"struc"+"tor"]('al' + 'er' + 't(\'' + 'hi there!' + '\')')()` – Konrad Borowski Sep 21 '14 at 11:57
-
5Yikes, there were social networking sites that restricted alert() but allowed eval()?! – joshden Apr 06 '16 at 14:48
Unless you let eval() a dynamic content (through cgi or input), it is as safe and solid as all other JavaScript in your page.

- 3,189
- 2
- 20
- 32
-
1While this is true -- if your content *isn't* dynamic, what reason is there to use eval for it at all? You could just put the code in a function and call it, instead! – Periata Breatta Oct 26 '16 at 16:22
-
Just for example - to parse returning value (JSON like, server defined strings, etc.) that came from Ajax call. – Thevs Oct 27 '16 at 12:34
-
2Oh, I see. I would call those dynamic because the client doesn't know ahead of time what they are, but I see what you mean now. – Periata Breatta Oct 29 '16 at 13:10
Along with the rest of the answers, I don't think eval statements can have advanced minimization.

- 5,709
- 12
- 53
- 82
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.

- 15,573
- 16
- 56
- 75

- 317
- 1
- 6
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.

- 113,588
- 46
- 195
- 237
-
1Only if your server-side security sucks. Client-side security is straight nonsense. – doubleOrt Sep 11 '17 at 23:38
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 executing eval()
on has come from a reasonable source, you're fine.

- 545
- 3
- 10

- 62,604
- 14
- 116
- 151
-
3
-
@Qix - running that test on my browser (Chrome 53) shows *eval* as somewhat faster than *parse*. – Periata Breatta Oct 26 '16 at 16:26
-
@PeriataBreatta Huh, strange. I wonder why. At the time I commented that wasn't the case. However, it's not unheard of for Chrome to get strange performance boosts in certain areas of the runtime from version to version. – Qix - MONICA WAS MISTREATED Oct 26 '16 at 16:36
-
A little old thread here, but from what I've read-- not claiming I traced it back myself-- JSON.parse in fact eval's it's input in the final stage. So efficiency-wise, takes more work/time. But security-wise, why not just parse? eval is an awesome tool. Use it for things that have no other way. To pass functions through JSON, there is a way to do it without eval. That second parameter in JSON.stringify lets you put a callback to run that you can check via typeof if it's a function. Then get the function's .toString(). There are some good articles on this if you search. – jdmayfield Feb 08 '18 at 05:07
If you want the user to input some logical functions and evaluate for AND the OR then the JavaScript eval function is perfect. I can accept two strings and eval(uate) string1 === string2
, etc.

- 30,738
- 21
- 105
- 131

- 41
- 1
-
You can also use Function() {}, but be careful when using these on the server unless you want users to take over your server hahahah. – aoeu256 Jul 19 '19 at 15:45
If you spot the use of eval() in your code, remember the mantra “eval() is evil.”
This function takes an arbitrary string and executes it as JavaScript code. When the code in question is known beforehand (not determined at runtime), there’s no reason to use eval(). If the code is dynamically generated at runtime, there’s often a better way to achieve the goal without eval(). For example, just using square bracket notation to access dynamic properties is better and simpler:
// antipattern
var property = "name";
alert(eval("obj." + property));
// preferred
var property = "name";
alert(obj[property]);
Using eval()
also has security implications, because you might be executing code (for
example coming from the network) that has been tampered with.
This is a common antipattern when dealing with a JSON response from an Ajax request.
In those cases
it’s better to use the browsers’ built-in methods to parse the JSON response to make
sure it’s safe and valid. For browsers that don’t support JSON.parse()
natively, you can
use a library from JSON.org.
It’s also important to remember that passing strings to setInterval()
, setTimeout()
,
and the Function()
constructor is, for the most part, similar to using eval()
and therefore
should be avoided.
Behind the scenes, JavaScript still has to evaluate and execute the string you pass as programming code:
// antipatterns
setTimeout("myFunc()", 1000);
setTimeout("myFunc(1, 2, 3)", 1000);
// preferred
setTimeout(myFunc, 1000);
setTimeout(function () {
myFunc(1, 2, 3);
}, 1000);
Using the new Function() constructor is similar to eval() and should be approached
with care. It could be a powerful construct but is often misused.
If you absolutely must
use eval()
, you can consider using new Function() instead.
There is a small potential benefit because the code evaluated in new Function() will be running in a local function scope, so any variables defined with var in the code being evaluated will not become globals automatically.
Another way to prevent automatic globals is to wrap the
eval()
call into an immediate function.

- 100
- 2
- 9
-
Can you suggest how I might evaluate a function-local dynamic variable name without eval? Eval (and similar) functions are last-resorts in most languages that contain them, but sometimes it's necessary. In the case of getting a dynamic variable's name, is any solution more secure? In any case, javascript itself is not for real security (server-side is obviously the main defense). If you're interested, here's my use-case of eval, which I'd love to change: https://stackoverflow.com/a/48294208 – Regular Jo Jan 17 '18 at 05:49
EDIT: As Benjie's comment suggests, this no longer seems to be the case in chrome v108, it would seem that chrome can now handle garbage collection of evaled scripts.
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
Garbage collection
The browsers garbage collection has no idea if the code that's eval'ed can be removed from memory so it just keeps it stored until the page is reloaded. Not too bad if your users are only on your page shortly, but it can be a problem for webapp's.
Here's a script to demo the problem
https://jsfiddle.net/CynderRnAsh/qux1osnw/
document.getElementById("evalLeak").onclick = (e) => {
for(let x = 0; x < 100; x++) {
eval(x.toString());
}
};
Something as simple as the above code causes a small amount of memory to be store until the app dies. This is worse when the evaled script is a giant function, and called on interval.

- 166
- 1
- 13
-
1This does not seem to be the case in Chrome v108, which runs the V8 JS engine, same as Node. Though the eval version _seems_ to climb slightly faster, it took around 80 seconds for it to hit 10MB and then it garbage collected back down to the starting amount and continued running. Clicking the trashcan icon at the top left ("Collect garbage") also has the same effect of resetting the memory usage back to the original value. There doesn't appear to be any leakage. – Benjie Jan 13 '23 at 09:44
-
1Just tested it and you are correct, seems like this might no longer be the case. Thanks @Benjie – J D Feb 03 '23 at 19:05
This is one of good articles talking about eval and how it is not an evil: http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/
I’m not saying you should go run out and start using eval() everywhere. In fact, there are very few good use cases for running eval() at all. There are definitely concerns with code clarity, debugability, and certainly performance that should not be overlooked. But you shouldn’t be afraid to use it when you have a case where eval() makes sense. Try not using it first, but don’t let anyone scare you into thinking your code is more fragile or less secure when eval() is used appropriately.

- 66,568
- 69
- 184
- 301
eval() is very powerful and can be used to execute a JS statement or evaluate an expression. But the question isn't about the uses of eval() but lets just say some how the string you running with eval() is affected by a malicious party. At the end you will be running malicious code. With power comes great responsibility. So use it wisely is you are using it. This isn't related much to eval() function but this article has pretty good information: http://blogs.popart.com/2009/07/javascript-injection-attacks/ If you are looking for the basics of eval() look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

- 224
- 2
- 9
The JavaScript Engine has a number of performance optimizations that it performs during the compilation phase. Some of these boil down to being able to essentially statically analyze the code as it lexes, and pre-determine where all the variable and function declarations are, so that it takes less effort to resolve identifiers during execution.
But if the Engine finds an eval(..) in the code, it essentially has to assume that all its awareness of identifier location may be invalid, because it cannot know at lexing time exactly what code you may pass to eval(..) to modify the lexical scope, or the contents of the object you may pass to with to create a new lexical scope to be consulted.
In other words, in the pessimistic sense, most of those optimizations it would make are pointless if eval(..) is present, so it simply doesn't perform the optimizations at all.
This explains it all.
Reference :
https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch2.md#eval
https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch2.md#performance

- 2,118
- 3
- 23
- 32
-
No javascript engine cannot find and eval in the code with 100% guarantee. Therefore, it must be ready for it at any time. – Jack G May 10 '18 at 02:37
It's not always a bad idea. Take for example, code generation. I recently wrote a library called Hyperbars which bridges the gap between virtual-dom and handlebars. It does this by parsing a handlebars template and converting it to hyperscript which is subsequently used by virtual-dom. The hyperscript is generated as a string first and before returning it, eval()
it to turn it into executable code. I have found eval()
in this particular situation the exact opposite of evil.
Basically from
<div>
{{#each names}}
<span>{{this}}</span>
{{/each}}
</div>
To this
(function (state) {
var Runtime = Hyperbars.Runtime;
var context = state;
return h('div', {}, [Runtime.each(context['names'], context, function (context, parent, options) {
return [h('span', {}, [options['@index'], context])]
})])
}.bind({}))
The performance of eval()
isn't an issue in a situation like this because you only need to interpret the generated string once and then reuse the executable output many times over.
You can see how the code generation was achieved if you're curious here.

- 75
- 9
I would go as far as to say that it doesn't really matter if you use eval()
in javascript which is run in browsers.*(caveat)
All modern browsers have a developer console where you can execute arbitrary javascript anyway and any semi-smart developer can look at your JS source and put whatever bits of it they need to into the dev console to do what they wish.
*As long as your server endpoints have the correct validation & sanitisation of user supplied values, it should not matter what gets parsed and eval'd in your client side javascript.
If you were to ask if it's suitable to use eval()
in PHP however, the answer is NO, unless you whitelist any values which may be passed to your eval statement.

- 1,495
- 1
- 13
- 31
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.

- 101,441
- 24
- 103
- 129
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.

- 5,826
- 11
- 60
- 82
I won't attempt to refute anything said heretofore, but i will offer this use of eval() that (as far as I know) can't be done any other way. There's probably other ways to code this, and probably ways to optimize it, but this is done longhand and without any bells and whistles for clarity sake to illustrate a use of eval that really doesn't have any other alternatives. That is: dynamical (or more accurately) programmically-created object names (as opposed to values).
//Place this in a common/global JS lib:
var NS = function(namespace){
var namespaceParts = String(namespace).split(".");
var namespaceToTest = "";
for(var i = 0; i < namespaceParts.length; i++){
if(i === 0){
namespaceToTest = namespaceParts[i];
}
else{
namespaceToTest = namespaceToTest + "." + namespaceParts[i];
}
if(eval('typeof ' + namespaceToTest) === "undefined"){
eval(namespaceToTest + ' = {}');
}
}
return eval(namespace);
}
//Then, use this in your class definition libs:
NS('Root.Namespace').Class = function(settings){
//Class constructor code here
}
//some generic method:
Root.Namespace.Class.prototype.Method = function(args){
//Code goes here
//this.MyOtherMethod("foo")); // => "foo"
return true;
}
//Then, in your applications, use this to instantiate an instance of your class:
var anInstanceOfClass = new Root.Namespace.Class(settings);
EDIT: by the way, I wouldn't suggest (for all the security reasons pointed out heretofore) that you base you object names on user input. I can't imagine any good reason you'd want to do that though. Still, thought I'd point it out that it wouldn't be a good idea :)

- 543
- 6
- 14
-
4this can be done with `namespaceToTest[namespaceParts[i]]`, no need for eval here, so the `if(typeof namespaceToTest[namespaceParts[i]] === 'undefined') { namespaceToTest[namespaceParts[i]] = {};` the only difference for the `else namespaceToTest = namespaceToTest[namespaceParts[i]];` – user2144406 Apr 14 '16 at 14:08