/

HTML / CSS / JavaScript Tutorial

JavaScript Global method: eval()

[this page | pdf | back links]

The JavaScript Global eval() method evaluates or executes an expression or set of JavaScript statements.

 

It has the following syntax with the following parameters:

 

eval(str)

 

Parameter

Required / Optional

Description

str

Required

String representing an expression or set of statements to evaluate / execute. If the argument is not a string, then it is left unchanged.

 

It is not appropriate to call eval() to evaluate an arithmetic expression, as JavaScript evaluates such expressions automatically.

 

eval() should be called sparingly. For example, it executes codes passed to it with the privileges of the calling algorithm, which can be exploited by a malicious party. It also invokes the JavaScript interpreter, which can frustrate modern browsers’ ways of optimising code execution.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
document.getElementById("Example").innerHTML =
  'var x = eval("var a = 10; var b = 2; a * b");'
document.getElementById("Result").innerHTML = eval("var a = 10; var b = 2; a * b");
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodGlobalEval() {
 return (eval("var a = 10; var b = 2; a * b") == 20);
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile