Thoughts from the office by Ed Ball
Thursday, March 03, 2005

Since new object properties can be created at will, a plain old Object is quite useful in JavaScript.

One common use of an Object is as a simple data structure. For example, if you want to return multiple values from a function, you can return an object with multiple properties:

function SplitAt(str, n)
{
  var obj = new Object;
  obj.Before = str.substring(0, n);
  obj.After = str.substring(n + 1);
  return obj;
}

Or, using the abbreviated syntax:

function SplitAt(str, n)
{
  return { Before : str.substring(0, n), After : str.substring(n + 1) };
}

Another common use of an Object is as an associative array; specifically, a mapping from strings to objects.

var map = {};
map["George Washington"] = 1789;
map["John Adams"] = 1797;

Or:

var map = { "George Washington" : 1789, "John Adams" : 1797 };

To see if a string is represented by an associative array, you could simply check that it isn’t undefined (e.g., map["Ed Ball"] !== undefined), but a property can be explicitly set to undefined, so you should use the in statement (e.g., "Ed Ball" in map).

To remove a string from an associative array, use delete (e.g., delete map["Ed Ball"]).

To see all of the strings represented by an associative array, use for...in:

for (var str in map)
  write(str + " (" + map[str] + ")");

When using an Object as an associative array, make sure that your strings will never be the same as the name of a built-in property of Object, e.g., "toString" or "prototype". Why? Well, for example, unless it has been overwritten, map["toString"] evaluates to a Function object instead of undefined. Furthermore, "toString" in map will always return true, but for...in will never enumerate "toString", and delete map["toString"] will always fail.

Also keep in mind that future versions of JavaScript could add new built-in properties; for example, version 5.5 added "hasOwnProperty". When I want to make absolutely sure that I won’t have any conflicts with built-in properties, I prefix the string with a space character – no built-in property will ever start with a space, after all.

function Get(map, str) { return map[" " + str]; }
function Set(map, str, obj) { map[" " + str] = obj; }
function Has(map, str) { return (" " + str) in map; }
function Erase(map, str) { delete map[" " + str]; }
function Find(map, obj)
{
  for (var str in map)
    if (map[str] == obj)
      return str.substring(1); // remove space
}
3/3/2005 1:23:58 PM (Pacific Standard Time, UTC-08:00) | Comments [0] | Code | JavaScript#
Search
Archive
Links
Categories
Administration
Blogroll