Don't be eval()
12 Comments
Comments are ordered by helpfulness, as indicated by you. Help us pick out the gems and discourage asshattery by voting on notable comments.
Got something to add? You can leave a comment below.
Troy
Dustin Diaz
To think that there’s people out there that really do think it’s B.A.D…. oh well.
Anyway, Simon, thanks for putting up a great 7th day. I’ll pass this along to the Sunnyvale folk if they haven’t already found it.
brandon
eval() is great for JSON:
http://en.wikipedia.org/wiki/JSON
bo
I agree with Justin. There are already some examples of using eval() with AJAX. I say it is just as “eval” missusage, executing magicly retrieved code… xmlhttp.responseText should stay text – parse it and do the work in the calling script.
Le Roux
I also blogged about this a while back: eval considered harmful
Mark Giblin
People who claim eval() is evil and bad for javascript or should be removed DO NOT and I repeat DO NOT UNDERSTAND ITS PROPER USE.
Like any tool in the tool box, it can be abused and is very often so abused by those who don’t know how to achieve a goal or have something to hide like script kiddies that obfuscate code.
I have to point out that one of the examples you give is wrong. It results in an “Uncaught ReferenceError: foo is not defined “ error notice.
As for the gentleman passing comment about “AJAX should be data”, I have to point out that anything the server sends “IS DATA” even if its binary data, its still data. If AJAX relied on binary data then you would have to have larger transcoding routines to make anything the server sends legible.
The point of sending TEXT based data is very obvious :)
Chad
Sure, this is wrong:
var propertyName = ‘myProperty’;
eval(‘object.’ + propertyName); ——- but what about this?
var propertyName = ‘myChildObject.myProperty’
eval(‘object.’ + propertyName); ?
How else would I get to myProperty if all I have is the string, and the data is inside of the local var ‘object’?
Levi
Thanks for this post! I especially appreciated the part explained what eval() IS good for, as I can’t seem to find any good explanations for that on the web!
Aaron Schmidt
I’ve always been afraid of eval just because it seems like such a hack. Thanks for outlining the alternatives.
Mee
Google Suggest also uses eval() when returning array of possible hits.
Should be used with thought, as pointed.
Alexey Feldgendler
The link http://www.scss.com.au/family/andrew/webdesign/xmlhttprequest/ is broken: 403 Forbidden.
Justin Perkins
eval() doesn’t simplify your code, it just hides it inside CPU-intensive strings.
AJAX responses ought to be data, it seems funny to pass back Javascript (even if it’s just a function call) for execution.
Very nice. People who develop apps should thing about the functions they use in any language before just using them.