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
function func() {
let a = 4;
let b = 4;
let value = eval( new String(a * b));
console.log(value);
}
func();
|
Output:
"16"
Example 2:
Javascript
function func() {
let a = 2;
let b = 2;
let value = eval( new String(a + b));
console.log(value);
}
func();
|
Output:
"4"
Example 3:
Javascript
function func() {
let a
let b
let value = eval( new String(a + b));
console.log(value);
}
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!