From PHP development I know that eval is evil and I've recently read What constitutes “Proper use” of the javascript Eval feature? and Don't be eval. The only proper use of eval I've read is Ajax.
I'm currently developing a visualization tool that lets users see how polynomials can interpolate functions:
I use eval for evaluation of arbitrary functions. Is this a legitimate use of eval? How could I get rid of eval?
I want the user to be able to execute any function of the following forms:
- a x^i with a,i in R
- sin, cos, tan
- b^x with b in R
- any combination that you can get by
- adding (e.g. x^2 + x^3 + sin(x)),
- multiplying (e.g. sin(x)*x^2) or
- inserting (e.g. sin(x^2))
eval
is a legitimate way of doing nearly everything (in absence of proper macros).eval
.eval
is without a doubt the most powerful, but it's also more brittle and dangerous than more specialized tools. For example, there is no reason to useeval
for getting an attribute dynamically, as ineval('obj.'+attrname)
- that's whatobj[attrname]
is for.