Tuesday 28 August 2018

JavaScript: Evaluating expressions

JavaScript provides eval function, which takes a string and evaluates the expression.

Syntax
eval(string)

What Can I do using eval?
         a. You can evaluate an expression.
         Ex: eval("2+5*7");
        
         b. You can define a variable.
         Ex: eval("var x = 10");
        
         c. You can define a function.
         Ex: eval("function inc(x) {return x+1}");
        
In addition to these, it replaces the variables with values while evaluating expressions.
Ex:
var a=10, b=20;
eval("a+b") evaluates to 10+20 = 30.

eval.html

<!DOCTYPE html>

<html>

<head>
    <title>eval Example</title>
</head>

<body>
    <script>
        var a = 10;
        var b = 20;

        eval("var c=30;"); // Define a variable
        var sum = eval("a+b"); // Evaluate an Expression
        var expression = eval("2+5*7"); // Evaluate an Expression
        eval("function inc(x){return x+1;}"); // Define a function

        document.write("c = " + c + "<br />");
        document.write("sum = " + sum + "<br />");
        document.write("expression = " + expression + "<br />");
        document.write("inc(10) = " + inc(10) + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following text.

c = 30
sum = 30
expression = 37
inc(10) = 11

Previous                                                 Next                                                 Home

No comments:

Post a Comment