Professional JavaScript | 10 | WebReference

Professional JavaScript | 10

1234
[previous] [next]

Professional JavaScript

eval() Concepts

Interpreted languages like JavaScript have a very useful peculiarity that compiled languages lack. Because the interpreter exists as part of the program that runs the script, the possibility exists that more interpretation of JavaScript statements can occur after the script has been read and started. We might call this dynamic or run-time evaluation to emphasize that it happens after the script gets going. Sometimes this might be called piggyback embedding.

Simple Dynamic Evaluation – Maps

Chapter 2 discussed how objects and arrays have interchangeable syntax. Recall that these two statements are equivalent:


object.property = "stuff"
array["property"] = "stuff"

Because the argument supplied to the array is an expression, it's possible to do handy things like this:


var all_cars = new CarCollection;
var car;
while ( (car=get_car_name()) != "" )
  all_cars[car.toLowerCase()] = get_registration(car);
 

In the last line, the variable car is used to create the property names of the all_cars object so that one property matches each car in the collection. Then each of those properties is set to a related value for that car – in this case the registration number. So if these collectable cars existed:


Model T Ford	A234
Goggomobile	MCI 223
Austin Lancer	JG 33

Then the properties of the all_cars object would be "model t ford", "goggomobile" and "austin lancer". Later we could refer to those properties as follows to dig out the related information:


var x = "model t ford";
all_cars[x];                  // "A234"
all_cars.goggomobile;         // "MCI 233"
all_cars["austin lancer"];    // "JG 33"

Effectively, the properties of the object depend on the data available, and that might not be known until runtime (if the user enters it, for example).

This ability to interchange between data and variable names is a powerful and common feature of scripting languages. In particular, this example shows a very commonly used structure dubbed alternatively a map, mapping, associative array, hash, or merely dictionary. The point is that it lets you get at a data value (a property's value) based on a unique key value (the property name), and it lets you keep a bunch of such pairs neatly together. It is a simple form of unordered index. Mathematicians say "There is a mapping from the set of collectable cars to the set of registration numbers for those cars". Whatever.

Note that in this example we'd be in trouble if a second Model T Ford turned up. That second car would have the same property name as the first and the system breaks down. That's why this approach is nearly always used for data that has a set of unique values only. Plenty of data is like that.

1234
[previous] [next]
and
Created: February 12, 2001
Revised: February 16, 2001

URL: http://webreference.com/programming/javascript/professional/chap3/