Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptIs JavaScript’s eval() evil?

Is JavaScript’s eval() evil?

The eval() is an in-built JS function that evaluates arguments that are expressions and executes one or more statements given to it as arguments. 

Reason eval() is considered evil: There are several problems possessed by the use of eval() and out of all performance and code injection are considered the most problematic. Performance- since the script compiler cannot pre-compile eval(), it runs the compiler even when the code is compiled during run-time. Even though not much but this still degrades the performance.

It is Complicated– most cases in which eval() is used don’t even require it that badly. So, in cases like these, an alternative approach is preferred more than eval(). Code injection- eval() runs string as a code and it is way easier for hackers to get into privileged information just by the use of eval(). This is a big security threat when a program takes input from the user and is running on the client side. This in turn can go on to manipulate the original program itself.

Harder to debug- while debugging it requires double work.

Example: In this example, we will see why the eval function is considered evil in Javascript.

Javascript




<script type="text/javascript">
    var a=eval("4+3");
    console.log(a);
</script>


Output:

7

When eval() not evil: For cases where you are running the program on your browser. Also, you need to be very careful not to pass any information that can give rise to code injection and manipulate the program in any way possible. It is generally preferred to use an alternate function in place of eval() if there is any function that can give out the same result as eval(). Closures, object-oriented techniques, and functional techniques generally are capable of replacing eval(). For cases where this can’t be done and using eval() is the only way possible it is preferred to the passcode that will not manipulate the DOM in any way.eval() is evil if running on the server using input submitted by a client that was not created by the developer or that was not sanitized by the developer. eval() is not evil if running on the client, even if using unsanitized input crafted by the client. Obviously, you should always sanitize the input, as to have some control over what your code consumes.

RELATED ARTICLES

Most Popular

Recent Comments