Eval is evil. - Some frustrated JavaScript engineer
I recently read this quote on the internet and although it is funny, it got me thinking why would someone say this? Thus this post. In this post, we will see why we should not use eval in JavaScript.
Introduction to eval
To understand why to avoid eval, we first need to understand what eval is. We are not going deep into what eval is and why it exists. We will see its definition and a simple example. If you want to learn more about eval, here is a great post on MDN.
The eval() function evaluates JavaScript code represented as a string.
Eval is a function in JavaScript that expects a string as a parameter and executes that string as code. If you pass an expression to it, it will execute that expression. If you pass multiple JavaScript statements to it, it will execute those statements. As simple as that. Let us check an example to understand more.
console.log(eval('2 + 2'));
// Output: 4
Why not use eval?
After learning about the eval, you might be wondering why this post is against using eval? After all, it is such a powerful feature.
But as we all know, Great power comes at a cost. In evalβs case, the costs are performance, security, and difficulties in debugging. Let us look at them one by one.
Performance
As we can see, the string passed to eval for execution is dynamic. So there is no way our JavaScript code knows about this string. That is why, when JavaScript wants to execute this string, it has to interpret/compile that string at runtime. This tends to be very expensive in terms of performance if the string is complex.
Security risks
Usage of eval involves pretty high risks of running malicious code. Let us say you are accepting an expression from the user in an input box. And some mischievous user types in an infinite loop. This is going to be very dangerous especially if eval is used on the server-side.
Difficulties in debugging
Let us all admit that we have spent hours debugging the smallest bugs like missing semicolons. Imagine finding bugs that are caused by the dynamic code that JavaScript is trying to execute. If the eval is causing some side effects in your runtime environment, it gives us very little room for finding the issues.
Are there any other alternatives?
Fortunately, there is an alternative with window.Function which will almost do the same thing. But this is a simple alternative. There are things that are only possible with eval. But be sure to be very careful when using eval and only use it if it is an absolute necessity. You will probably find better alternatives on StackOverflow.
This article was originally published here. For more such interesting reads, visit my blog.
Top comments (0)