top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of eval function in JavaScript?

0 votes
513 views
What is the use of eval function in JavaScript?
posted Jul 29, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The eval function is used to execute JavaScript source code.
Syntax:

eval(expr)

Parameter:
expr :
The expr is a string represent a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. We should not call eval to evaluate an arithmetic expression ( 5 * 9 + 5-4) as JavaScript evaluates arithmetic expressions automatically. Note that the parameter expr argument is optional. If there is no argument, eval returned, "undefined".

Do not use eval()

eval() is sluggish and prone to security threats, and thus not recommended to be used. Here are why it is said so:

i) Code passed to the eval is executed with the privileges of the executer. So, if the code passed can be affected by some malicious intentions, it leads to running malicious code in a user's machine with your website's privileges.

ii) A malicious code can understand the scope with which the code passed to the eval was called. Which in turn, may raise security threats.

iii) eval has to call the JS Interpreter, thus making it sluggish.

Example ofeval() funciton:-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">  
<head>  
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />  
<title>JavaScript: eval function example-1</title>  
</head>  
<body>  
<h1 style="color: red">JavaScript  eval() function example-1</h1>  
<hr />  
<script type="text/javascript">  
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[ 
eval("language = 78; math = 89;  science=90; document.write('Total marks : '+(language + math + science));"); 
//]]>  
</script>  
</body>  
</html>  
answer Jul 30, 2014 by Rahul Singh
...