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.writ开发者_开发问答e("<br />" + (2+2);
</script>
</body>
</html>
Eval allows you to execute command stored in variable:
<script type="text/javascript">
var cmd = "2+2";
document.write("<br />" + eval(cmd));
</script>
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.
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...
With 'eval', you can do things like this:
<html>
<body>
<script type="text/javascript">
var command = prompt('input command');
eval(command);
</script>
</body>
</html>
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
精彩评论