Open In App
Related Articles

JavaScript eval() Function

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

Note:

eval(): This function was used to evaluate a string as JavaScript code, but it is now considered deprecated because it can introduce security vulnerabilities and is often unnecessary.

Syntax:

eval(string);

Parameters:

This function accepts 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. 

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"

Example 1: Below is an example of eval().

Javascript

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

                    

Output
[String: '16']

Example 2: Below is an example of eval().

Javascript

// JavaScript to illustrate eval() function
function func() {
 
    // Original string
    let a = 2;
    let b = 2;
 
    // Finding the sum
    let value = eval(new String(a + b));
    console.log(value);
}
// Driver Code
func();

                    

Output
[String: '4']

Example 3: Below is an example of eval().

Javascript

// JavaScript to illustrate eval() function
function func() {
 
    // Original string
    let a
    let b
 
    // Finding the Summation
    let value = eval(new String(a + b));
    console.log(value);
}
// Driver code
func();

                    

Output
[String: 'NaN']

We have a complete list of Javascript Function methods, to check those please go through this Javascript Function Complete reference article.

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Mozilla Firefox
  • Safari
  • Opera

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic Guide to JavaScript.



Last Updated : 09 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads