1.

How to handle exceptions in JavaScript?

Answer»

The eval() function is used in JavaScript to evaluate or execute an argument. The method evaluates the expression, if the argument is an expression, else for arguments as statements, it executes the statements.

The parameter in the eval(string) function is a string, which can be an expression, variable, statement, or sequence of statements:

eval(string)

Note: Do not call eval() method to evaluate an ARITHMETIC expression

Let’s say we have the following two variables:

var val1 = 20; var val2 = 7;

Now, with a new variable we will perform some calculations with the eval() method:

var calc1 = eval("val1 * val2") + "<br>"; var calc2 = eval("99 + val1") + "<br>";

The example demonstrates the role of eval() in JavaScript:

<!DOCTYPE html> <html> <body> <button onclick="SHOW()">Display</button> <p id="myid"></p> <script> function show() {     var val1 = 20;     var val2 = 7;     var calc1 = eval("val1 * val2") + "<br>";     var calc2 = eval("99 + val1") + "<br>";     var RES = calc1 + calc2;     document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The output displays a button, which on pressing GENERATES the following result: 

140 119

Let us see another example: 

<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() {     var val1 = 15;     var val2 = 10;     var calc1 = eval("30 * 3") + "<br>";     var calc2 = eval("val1 + val2") + "<br>";     var calc3 = eval("5 * val1") + "<br>";     var calc4 = eval("10 + val2") + "<br>";     var res = calc1 + calc2 + calc3 + calc4;     document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The output displays a button, which on pressing generates the following result:

90 25 75 20


Discussion

No Comment Found