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.
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.
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
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.