Using eval () in javascript: what are the pros and cons?

I recently knew this function and was surprised by its power, it was very useful to me, but after using it I heard comments that it was not safe.

I would like to know in this situation this use can cause security problems and if there is an alternative to eval () when you want to generate javascript code dynamically, but in a more secure way.

Example of use by my application:

var valPeriodos = "";
var next = ".next()";

for (i = 1; i <= numPeriodos; i++) {
    eval('var tdVal' + i + '=$(this).parent().parent().find(".vp1").parent()' + valPeriodos + ';');
    valPeriodos += next;
    eval('val_' + i + ' = tdVal' + i + '.find(".valInputOn").val()');
}

In this code I take values from a dynamic table that has columns according to the number of periods and I save them in variables.

Author: Joao Paulo, 2014-02-04

3 answers

I have to answer also because the eval() it is not as bad as many people think, it depends on how and where it is used. Driving a car is dangerous if you do not know how to do it.

For those who do not master javascript eval can scare. And then it is easier to generalize and say that one should never use it. Well, that's not the case.

Eval is one of the most powerful javascript tools. It is a parser itself. The biggest problem of eval arises when connected to communication with the server. But if you use eval in internal code functions, without external input eval can be very useful and safe.

It is worth mentioning (and taking into account) that any user can reach a site, open the console and run Evil Code with eval.

If you have eval in lines of code that link to a database for example, it is important to do to shield possible attacks. In these cases avoid eval.

The first part of my answer is positive to eval, this to say that there are cases where it is util (as here for example).

But it has weight cons:

  1. Misuse of eval can lead to code injection attacks

  2. More difficult to debug (since within eval the errors have no line indication)

  3. Slower than similar code without eval

  4. Hinders and limits code minification

At last it is worth mentioning that eval is used in hidden javascript. More on that in this question .

 14
Author: Sergio, 2017-04-13 12:59:43

The eval, in certain situations causes your code to be...

  1. ... more difficult to understand: javascript is being compiled on the spot, which, in addition to making it slower, makes it vary according to the variable that is inserted in the function;
  2. ... more insecure: ever heard of SQL Injection ? eval is an open door to that, only in another language;
    Using 'use strict' prevents an attacker from having access to private variables, but it does not protect global variables, so if you have to use eval validate the code before running it.
  3. ... harder to work with: tools like Closure Compiler and Uglify can't work with eval in certain situations. The function prevents these tools from finding the Defined Variables and organizing them.

But there are situations where the use eval is accepted-according to the style guide of the Google :

  • if you are programming a REPL, example:
!function r(i){i=prompt('Insira um comando:');if(i)alert(eval(i)),setTimeout(r)}()
  • if you are programming a code loader: RequireJS, for example, uses eval.

edit: an example code was added to the question, this answer this same code rewritten without using eval.

 14
Author: Gustavo Rodrigues, 2017-04-13 12:59:43

In the example you gave, the alternative to eval would be to use a vector instead of a bunch of separate variables:

var vals = [];
var tdVals = [];
var tdAtual = $(this).parent().parent().find(".vp1").parent()
//Vetores em Javascript são normalmente indexados começando do zero então mexi no seu loop.
for (i = 0; i < numPeriodos; i++) { 
    tdVals[i] = tdAtual;
    vals[i] = tdAtual.find(".valInputOption").val();
    tdAtual = tdAtual.next();
}

Some of the advantages that this code has compared to the version using eval:

  • it will be easier to debug. In case of an error, the debugger better points the line of code, you can mark breakpoints, inspect the contents of variables, etc.
  • it will be easier to use tools that analyze your code without running it, such as JSHint (I strongly recommend using such a thing if you are not using it!). Usually these tools are totally lost if they encounter an eval.
  • vectors are a first-class object in JS, unlike their dynamic variables. You can pass them from one side to the other, you can look at the tdVals.length instead of having to keep the value of the numPeriodos separately, etc.
  • the scope of your variables becomes clearer. You can see for yourself what the names of the two are vectors I am creating and it is easier to know if the variables are global and local.
  • the algorithm has become simpler and more efficient. Now it gives a next only for each td instead of 1 for the first, 2 for the second, etc.
  • I think it got easier to understand. A code using eval can potentially do anything, which means it has to be read more carefully.
 2
Author: hugomg, 2014-02-04 19:36:47