Skip to content
Related Articles

Related Articles

Javascript eval() Function
  • Last Updated : 06 Jul, 2020

Below is the example of the eval() function.

  • Example:




    <script>
        // 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));
            document.write(value);
        }
    // Driver code
    func();
    </script>                    
  • Output:
    16

The eval() function is used to evaluates 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)

Parameters: This function accept a single parameter as mentioned above and described below:

  • String: A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.

Return Value: The completion value of evaluating the given code is returned by using eval(). If the completion value is empty, undefined is returned.



Below examples illustrate the eval() function in JavaScript:

Example 1:

Input : eval(new String('2 + 2'));
Output: returns a String object containing "2 + 2"
Input : eval(new String('4 + 4'));
Output: returns a String object containing "4 + 4"

More example codes for the above function are as follows:
Program 1:




<script>
    // JavaScript to illustrate eval() function
    function func() {
  
        // Original string
        var a = 2;
        var b = 2;
  
        // Finding the sum
        var value = eval(new String(a + b));
        document.write(value);
    }
// Driver Code
func();
</script>                    

Output:

4

Program 2:




<script>
    // JavaScript to illustrate eval() function
    function func() {
  
        // Original string
        var a
        var b
  
        // Finding the Sumation
        var value = eval(new String(a + b));
        document.write(value);
    }
// Driver code
func();
</script>                

Output:

NaN

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Mozilla Firefox
  • Safari
  • Opera
My Personal Notes arrow_drop_up
Recommended Articles
Page :