Javascript | eval() Function


eval() is a function property of the global object.

  • The argument of the eval() function is a string.
  • If the string represents an expression, eval() 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:
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. 

Examples:

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"

Below Programs will illustrate the use of eval(): function more deeply:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

4

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

16


My Personal Notes arrow_drop_up

Work hard till success becomes easier to achieve

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.