Home  >  Article  >  Web Front-end  >  What is the usage of eval in javascript

What is the usage of eval in javascript

藏色散人
藏色散人Original
2021-09-03 15:07:045398browse

The eval function in JavaScript is used to calculate a certain string and execute the JavaScript code in it. The syntax of this function is "eval(string)", and the parameter string represents the string to be calculated.

What is the usage of eval in javascript

The operating environment of this article: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Usage of eval in javascript

The eval() function can calculate a certain string and execute the JavaScript code in it.

Syntax

eval(string)

Parameter string Required: The string to be evaluated, which contains the JavaScript expression to be evaluated or the statement to be executed.

Return value: The value obtained by calculating string (if any).

Explanation

This method only accepts original strings as parameters. If the string parameter is not an original string, then the method will return without any changes. Therefore please do not pass String objects as arguments to the eval() function.

The ECMAScript implementation is allowed to throw an EvalError exception if you try 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 will be thrown.

If the Javascript code passed to eval() generates an exception, eval() will pass the exception to the caller.

Tip: Although eval() is very powerful, it is rarely used in actual use.

Example

In this example, we will apply eval() on several strings and look at the returned results:

<script type="text/javascript">
eval("x=10;y=20;document.write(x*y)")
document.write(eval("2+2"))
var x=10
document.write(eval(x+17))
</script>

Output:

200
4
27

Recommended study: "javascript basic tutorial"

The above is the detailed content of What is the usage of eval in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn