Understanding the use of the function eval()
, I understand that it is to evaluate a string
as a Javascript expression, however, the usage orientation is not recommended .
An example of the use of the function would be the following code segment:
var refreshTime = 'setTimeout(function(){ console.log("Writing somehing every second!"); }, 1000);';
eval(refreshTime)
Is there any possible scenario where the use of Eval()
is an option, or in your case, necessary and/or required?
In the same way, a question that does not make me clear about the scope of the function is that timeout
it only executes once, and not every second as it should.
A very interesting question, I will venture to answer it and I hope to be up to it.
For the question:
Never , in the days when browsers didn't support all the features we have today, perhaps, we could have found a case where we might have needed it.
For example, let's say we have a JSON string, and we need to convert it to a value for use:
But today we can say that more than 90% of the browsers that are used support the syntax
JSON.parse()
But what if my JSON string comes in another format?
Let's say we get a string with this form
{name: "Carlos", username: "KacosPro"}
We found a use for it! Yes, but that JSON is not in the correct format and therefore it is not a valid JSON, the specification clearly says that in JSON a string is a sequence of zero or more Unicode characters, wrapped in quotes escaped doubles with a source backslash
Another use among several that we can find is to call a function dynamically, for example
But still we can find another way to do it
In conclusion
Not to mention that it is a potentially insecure function, since if it is not used carefully someone can execute code in our scipts .
For each use that can be found, we have a more efficient way to avoid it.
Yes , there may be several cases, for example the creator
JSON.parse()
uses it but after having sanitized it and checked if it is a valid JSON string. We can see what it says:Or in Spanish (feel free to edit if you find something wrong in the translation):
We can see its use here
Finally for your doubt
setTimeout()
executes the function when the timeout has elapsed and only executes it onceIf what you need is for it to be executed from time to time, you should use the function
setInterval()
, here is a practical example:Or if you want it to start after an action we can encapsulate it in a function
The eval() function is widely used to obfuscate code and make it less readable, for example in paid libraries!
It has many utilities example: webscraping ! When you make a request for a website, you get it as plain text. Can you do:
You can also see an online obfuscator .
and obfuscated it would be:
I will provide an updated answer and with a somewhat less bad option:
When to use eval?
Never , it is dangerous and there is really no reason to do it. Code executed using this function has global access.
But I already know the code to be executed, it's JS that I've downloaded from my own site.
So there is no reason to use eval, you can load the code dynamically and run it more efficiently.
What if, despite everything, I am in a scenario where I need to execute code that I have received as text?
The function
eval()
has global access and this is dangerous and also expensive (the code to be executed is very slow). A better solution is to create a function with the code that will have a local "scope":Bad idea:
eval("(" + obj + ")");
A slightly better idea:
Function('"use strict";return (' + obj + ')')();
In Javascript the Functions are " first-class-citizens ". That is, they are common objects that can be created and have specific properties. Calling this function is somewhat less expensive and much more secure, since access is restricted inside the function. The reason it's less expensive is precisely because eval forces the compiler to look at higher scopes if a given identifier exists, while Function doesn't, it only works with the local scope and the objects of
window
:It is interesting, because the only use that would theoretically justify its use is when the code to be executed is not previously known, perhaps because it is generated dynamically, for example on the server. It would be assumed that otherwise we put the code as code and not as a string.
In this context I mean that "theoretically it would justify its use" in the sense that it cannot be done in any other way than using
eval()
. In my opinion, this scenario means in 100% of cases that there is a design flaw. That is, in this sense it would never be justified.This fact (the code to be executed is not previously known) is precisely what makes it potentially "dangerous", the specifically "dangerous" fact is the possibility of an XSS attack (Cross Site Scripting, I recommend OWASP for detailed information).
That is to say, the only fact that would theoretically justify its use in the sense that it cannot be done in another way, is precisely the characteristic that would make it dangerous.
But dynamic code execution is not the only use, one of the uses is simply to abstract code or deliberately obfuscate it, as @Bryro mentions. In other words, it is code that can be done in another way .
As an example, this is one way to get the average of an array using
eval()
:It is code that can clearly be done without the need for
eval()
but its use makes it very short and concise. At least in most of the cases in which the code can be done in another way , that is to say that theoretically the , would not be necessaryeval()
, said code is not dangerous at all. That is the paradox of the matter. In general it would be "safe" when it is not "necessary".Finally, I clarify that I use the expressions "At least in most cases" or "In general" because not all the possibilities are known, if we look at OWASP, vulnerabilities are added periodically. What happens
eval()
is that it is a possible vector of an XSS attack, even in scenarios that we do not know yet, which is why it is insisted on not using it at all.I'm deliberately leaving out some very specific cases that I think are a bit out of the ordinary, which would be JavaScript sanboxing, and the implicit use of
eval()
in other functions. Sandboxing would be the case of the JavaScript code executor that exists right here on StackOverflow, in jsfiddle or similar, where the use ofeval()
or the constructorFunction
is mandatory. The implicit use would be in functions like.innerHTML
, where code is actually executed as a string by other functions.