Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does eval do and why its evil? [duplicate]

var myString = "x",
    myObject = {
        x: 10
    },
value = eval("myObject." + myString);
alert(value)
alert(myObject[myString]);

eval is evil

I have been reading about eval() function over the internet, but could not really grasp on what it actually does apart from "It Evaluates an expression".

Should we use eval() function only for numeric values?.

like image 526
theJava Avatar asked Aug 16 '13 09:08

theJava


2 Answers

eval() takes the string it is given, and runs it as if it were plain JavaScript code.

It is considered "evil" because:

  • It over-complicates things - Most cases where eval() is used, there would be a much simpler solution that didn't require it. This example in the question is a perfect case in point: there is absolutely no need for eval() for an expression like this. JS has perfectly good syntax for referencing an object property name as a string (myObject["x"] is the same as myObject.x).

  • It's much harder to debug - It's harder to work with it in a debugger, and even once you have managed to work out what's going on, you have you extra work to do because you have to debug both the eval'd code, and the code that generated the original string to eval.

  • It slows things down - The script compiler cannot pre-compile code in an eval(), because it doesn't know what the code will contain until it gets there. So you lose out on a some of the performance benefits in modern Javascript engines.

  • It is a hacker's dream - eval() runs a string as code. Hackers love this because it's much easier to inject a string into a program than to inject code; but eval() means you can inject a string, and get it to run as code. So eval() makes your code easier to hack. (this is less of an issue for browser-based Javascript than other languages, as JS code is accessible in the browser anyway, so your security model should not be based on your code being immutable, but nevertheless, injection hacks can still be a problem, particularly with cross-site attacks).

like image 90
Spudley Avatar answered Oct 04 '22 04:10

Spudley


In this case, just use myObject[myString].

eval is horrifically misused. Pretty much the only valid use for it that I've found is parsing JSON in older browsers.

like image 44
Niet the Dark Absol Avatar answered Oct 04 '22 04:10

Niet the Dark Absol