Open In App

Why should you avoid the JavaScript eval() function?

Improve
Improve
Like Article
Like
Save
Share
Report

What is the eval() function?

The eval() function is used to evaluate the expression. If the argument represents one or more JavaScript statements, eval() evaluates the statements. We do not call eval() to evaluate an arithmetic expression. JavaScript evaluates arithmetic expressions automatically.

Syntax:

eval(string)

Example:

Javascript




// JavaScript to illustrate eval() function
    function func() {
      
        // Original string
        var a = 4;
        var b = 4;
      
        // Finding the multiplication
        var value = eval(new String(a * b));
        console.log(value);
    }
    // Driver code
    func();


Output

[String: '16']

Why is the eval() function a bad choice?

There are mainly 4 reasons why eval() method should be avoided:

1. Prone to Injection Attack:

Consider you have created a code that uses the value entered by the user to evaluate a result using the eval() method. Now, what if the user enters some unwanted value, which can lead to an unexpected outcome, such as an infinite loop? This will lead to a system crash and hence an overall shutdown.

2. Very slow:

If you enter two integers to find their sum using the eval() method, the result will be almost instantaneous. But since Javascript allows the use of all types (numbers, functions, objects, etc), the use of the eval() method will comparatively slow down the process.

3. Not easy to debug:

Since you are using the eval() method to render your code, it does not have proper line numbers or instructions. As a result, when trying to debug for error, it will always just show the overall eval() method as the point of error.

4. Not possible to optimize:

Since you cannot detect the error or debug the eval() method easily, you won’t be able to optimize your code easily as well. As a result, it will lead to extra effort, time and force.

What is the alternative?

  • Avoid using eval() for user input
  • If in any case, you need to use eval() for user input, use JSON parsing to parse the input value first and then detect for any unexpected values.
  • Try writing a hard code for the eval() method if possible.

Last Updated : 14 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads