hanhu
hanhu

Reputation: 255

What is the use of eval function inside Javascript?

<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>

Upvotes: 1

Views: 1226

Answers (5)

patwork
patwork

Reputation: 125

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

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

Upvotes: 1

Niklas
Niklas

Reputation: 30012

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

Upvotes: 0

chrisfrancis27
chrisfrancis27

Reputation: 4536

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...

Upvotes: 1

Ēriks Daliba
Ēriks Daliba

Reputation: 718

Eval allows you to execute command stored in variable:

<script type="text/javascript">
var cmd = "2+2";
document.write("<br />" + eval(cmd));
</script>

Upvotes: 2

jAndy
jAndy

Reputation: 236132

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.

Upvotes: 1

Related Questions