background
|
|
Hosting
My-Hosts.com
Cheap Hosting, domain registration and design. Check this out for more details.
More icon

bonsai
The Element
A small area for Bonsai related material.
More icon
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
Eval

The Mysteries of Eval

eval is really interesting and weird. It's used all the time in complicated scripts, so it'll be cropping up lots in future lessons. eval takes a string and evaluates it. Here's a simple example:


var the_label = "five";

var five = 5;

var the_sum = 10 + eval(the_label);

alert("The sum is " + the_sum);

The line: the_sum = 10 + eval(the_label) means "take the variable that's in the_label and evaluate it." When you evaluate "five" you get the value of the variable named five. Breaking it down, it goes like this:

  1. the_sum = 10 + eval(the_label);
  2. the_sum = 10 + eval("five");
  3. the_sum = 10 + 5;
  4. the_sum = 15

Let's look at the eval in the select example; the line:


var the_array = eval(the_array_name);

Let's say that you pulled the pulldown select to the word "Fish." The onChange event handler would be triggered, calling the swapOptions() function with the word "Fish." Inside swapOptions, the parameter the_array_name would be set to "Fish." Then, when the eval is reached, the variable the_array would be set to the Fish array. If we had just done this:


var the_array = the_array_name;

the_array would have equaled the string "Fish" instead of the Fish array.

Read this over if it doesn't make sense to you. Knowing how to use eval will boost you from junior JavaScript programmer to intermediate JavaScript programmer.

Back to the onChange handler.