Monday, September 23, 2024
Google search engine
HomeLanguagesJavascriptJavaScript eval() Function

JavaScript eval() Function

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. 

Example:

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"

The below examples illustrate the eval() function in JavaScript

Example 1: 

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:

"16"

Example 2: 

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:

"4"

Example 3

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:

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments