25
Recently I met this function and I was surprised by its power, it was of great use to me, but after using it I heard comments that it was not safe.
I would like to know in situation this use can cause security problems and if there is 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 save them in variables.
Please include some examples where you think Eval was of great use. So you can point out the pros and cons more concretely. The problem with Eval is that in most cases generating code dynamically is a bad idea because it is much simpler to think about static code and you have to worry less about escaping inputs that comes from the user.
– hugomg
Here’s an example. If I were to do it in a traditional way, I would spend dozens of lines of code. Besides, if you needed some maintenance it would be much more complicated to change line by line.
– Joao Paulo
It is possible (and advisable) to avoid
eval
in your example, even keeping the loop. But this requires changes to other parts of the code (array or object instead of variablesval_N
).– bfavaretto
What is in this variable valperiodos? I’m not understanding your example.
– hugomg
I added to the code @missingno
– Joao Paulo