Using the Java Script eval() Function
By Stephen Bucaro
The Java Script eval() function accepts a string argument. If the string is an expression,
i.e. numbers (may be literal or variable names) and operators that evaluates to a single value,
eval() evaluates the expression. If the string contains JavaScript statements, i.e. commands
or functions, eval() executes the statements.
Shown below is the syntax of the eval() function:
eval(string)
Shown below is an example of code that uses eval() to evaluate an expression:
<script type="text/javascript">
var num = 3;
var res = eval(num * 4);
alert(res);
</script>
You might think that you could easily code a calculator by submitting the contents of a
form text box directly as an argument to the eval function, but this would not be a good
idea because eval also executes the statements. For example the XMLHttpRequest function used
in Ajax development gives access to the server.
Shown below is an example of code that uses eval() to execute statements:
<script type="text/javascript">
eval("min=0; max=3; document.write(Math.floor(Math.random() * (max - min + 1) + min))");
</script>
In the code above, a string containing the Math objects .random() function and .floor()
function, and the document's .write() function is passed to the eval() function. The eval()
function executes the code in the string which generates a random number between 0 and 3
and writes it to the document.
More Java Script Code: • Extract Part of a String • Java Script Math.tan Method • Convert a Number to a String • Java Script Trigonometric Methods • The break Statement • Accessing Web Page Elements • Find a Character or a Substring Within a String • Use moveBy Method to Move Window by a Specific Offset • Use Escape to Replace Dangerous Characters • The switch / case Structure
|