Suite101

The eval() Function


© Muhammad Ali Shah

  • Level: Intermediate
  • Skills Required: Functions


Abstract:

Todays article discussed the built in eval function which lets you define and execute code on the fly. In complex and extremely rare cases, a programmer may not know in advance what code should be executed. Depending on values of different variables a particular statement may need to be executed at run time. This is where eval function comes in.


Function Explained:

Although most of the functions in JavaScript are actually methods, eval is different; it is a top-level function defined in JavaScript. It doesn't belong to any object.

This function accepts a single argument: a string that contains the code to be executed. The following example domonstrates string creation and evaluation using this function.

<html>
<head>
</head>

<body>
<script language="JavaScript">
   var stmt = "alert ('Did you get this');"
   eval (stmt);
</script>
</body>
</html>



This simple code says a lot. We define a string variable, namely stmt and assign it JavaScript code for displaying an alert message. This assignment is a normal operation; i.e., there are no effects other than changing the stmt's value.

Next comes the call to eval function. We pass it on our string. The web browser first tries to parse the string and understand what it means. It then carries out the task, which, in our case, is to display an alert message. Note that the value of the stmt variable can be given at run time. It may even come from a text box.


Last Words:

Very few languages allow polymorphic code - code that can change itself. Though, the usage is rare but this function fits very nicely in situations where you execute code depending on the input from the user and multiple if's become increasingly complex.

Go To Page: 1


The copyright of the article The eval() Function in JavaScript is owned by . Permission to republish The eval() Function in print or online must be granted by the author in writing.

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo