Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

When Should I Use Eval()?

DZone's Guide to

When Should I Use Eval()?

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

NEVER.

Got that off my chest.

eval() 

This 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. 
  • In Javascript, eval() forces the engine to drop into Interpreter mode, which slows down your application, and it will remain slow, as there's no opportunity for optimization-level caching to take place.
  • It's a bugger to debug, because there are no line numbers.
  • In Javascript (client-side), eval() is dangerous because it exposes you to cross-site scripting attacks.  
  • 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. 

Horrifying.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Tom O'connor, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}