eval Revisited

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 label = "five";
var five = 5;

var sum = 10 + eval(label);

alert("The sum is " + sum);

The line: sum = 10 + eval(label) means "take the variable that's in 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. sum = 10 + eval(label);
  2. sum = 10 + eval("five");
  3. sum = 10 + 5;
  4. sum = 15

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

var theArray = eval(theArrayName);

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 theArrayName would be set to "Fish." Then, when the eval is reached, the variable theArray would be set to the Fish array. If we had just done this:

var theArray = theArrayName;

theArray 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. There will be more examples later on demonstrating this very idea because it is so powerful and important.