1
<html>
<body>
<script type="text/javascript">
document.write("<br />" + eval("2+2"));
</script>
</body>
</html>

This gives me output as 4.

If i remove the eval function and run the same thing know it gives me the same output that is 4

<html>
<body>
<script type="text/javascript">
document.write("<br />" + (2+2);
</script>
</body>
</html>

5 Answers 5

2

Eval allows you to execute command stored in variable:

<script type="text/javascript">
var cmd = "2+2";
document.write("<br />" + eval(cmd));
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

it does not necessarily need to be stored in a variable.
Agree, but wanted to illustrate benefit of eval()
1

Your observation is pretty correct. eval() does nothing else than to evaluate Javascript code. Therefore the outcome is identical. However, the usage of eval() is pretty frowned upon. That is for security and performance reasons.

For instance, a Javascript engine (at least most of them) always trys to optimize your code in terms of access performance. Without going to deep here, accessing a pretty deep scope chain property is costly, so engines will optimize that access with hash lookup tables. By invoking eval() this mechanism can no longer be used and therefore, it's slower to lookup the property.

That is only one example why the usage of eval() is not recommendable, there are plenty more.

Comments

1

eval tries to execute a string as if it were a script - in your example (2+2) is not a string so it has no effect.

Also, eval is evil...

Comments

1

With 'eval', you can do things like this:

<html>
<body>
<script type="text/javascript">
    var command = prompt('input command');
    eval(command);
</script>
</body>
</html>

Comments

0

eval() takes a string and evaluates it as if it wasn't one. (2+2) is not a string.

console.log (typeof (2+2)); // returns number

console.log (typeof "2+2"); // returns string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.