eval is something of a hybrid between an expression evaluator and a statement executor. It returns the result of the last expression evaluated (all statements are expressions in Javascript), and allows the final semicolon to be left off.
Example as an expression evaluator:
foo = 2;
alert(eval('foo + 2'));
Example as a statement executor:
foo = 2;
eval('foo = foo + 2;alert(foo);');
One use of JavaScript's eval is to parse JSON text, perhaps as part of an Ajax framework. However, modern browsers provide JSON.parse
as a more secure alternative for this task.
source
With that in mind the only real reason I can see you wanting to use eval()
is for executing user input.. but that leads to serious security risks... so in short I would say eval()
(in javascript at least) has become a mute function; replaced by the many specific functions that would have invoked you to use eval()
in the past.
Another idea.
You could possibly use it to execute pure js being returned by ajax
your server could pass back a string containing "alert('hello world');" and you could eval(returnData);
.