When should I use eval()?
Monday, 7th October 2013
That's got that off my chest.
is possibly the most dangerous thing ever. It's basically a way to execute arbitrary code from a string or variable.
Here's a few reasons why it's dangerous.
It leaves you open to injection attacks.
It's a bugger to debug, because there's no line numbers.
In server-side code, eval() is downright lethal, because it exposes the entire server to anything that the user wants to run.
Python has a "safer" eval, called literal_eval in the ast module, which allows for parsing of user-provided data, without having to write a parser to sanitise it yourself. I'd still avoid it like the plague, given a choice.
This is all fairly fresh in my mind, because I discovered a snippet of code somewhere (not disclosing where, as I'm doing the responsible thing and doing the disclosure properly), that was along the lines of
var jsonData = eval ("(" + string + ")");
Apparently JSON.parse() isn't good enough for them.