Let’s first look at a function of JS
JavaScript eval() function
Definition and usage The
eval() function can calculate a certain string and execute the JavaScript code in it.
Syntax
eval(string)
Parameter Description
string Required. A string to evaluate that contains a JavaScript expression to evaluate or a statement to execute.
Return value
The value obtained by evaluating string (if any).
Explanation
This method only accepts original string as parameter. If the string parameter is not an original string, then this method will return without any changes. Therefore please do not pass String objects as arguments to the eval() function.
ECMAScript implementations allow an EvalError exception to be thrown if an attempt is made to override the eval property or assign the eval() method to another property and call it through that property.
Throws
If there are no legal expressions and statements in the parameters, a SyntaxError exception is thrown.
If eval() is called illegally, an EvalError exception is thrown.
If the Javascript code passed to eval() generates an exception, eval() will pass the exception to the caller.
Tips and Notes
Tip: Although the function of eval() is very powerful, it is rarely used in actual use.
Example
Example 1
In this example, we will apply eval() on several strings and see the returned results: