Nima Dilmaghani’s Technology Blog

Enums in JavaScript

Posted in AJAX, ASP.NET, ATLAS, javascript by nimad on October 2, 2007

Enums, (enumerated types) are very simple but incredibly useful programming constructs. However, while the EcmaScript specification has the enum keywork reserved, they have not implemented it in the language. While Microsoft’s JScript has an implementation of Enum, I recommend not using it since your code will not work in browsers other than IE. However by using associative arrays you can get a good deal of the enum functionality easily:

var myEnum =
First : 0,
Second : 1,
Third : 2

both return a 2

If you really want enums, the Microsoft AJAX Library implements them. You first declare the enumeration and then register it with the class the enum belongs to. Here is an example from the Microsoft Ajax Control Toolkit:

// Create an alias for the namespace to save 25 chars each time it’s used since
// this is a very long script and will take awhile to download
var $AA = AjaxControlToolkit.Animation;

$AA.FadeEffect = function() {
/// <summary>
/// The FadeEffect enumeration determines whether a fade animation is used to fade in or fade out.
/// </summary>
/// <field name=”FadeIn” type=”Number” integer=”true” />
/// <field name=”FadeOut” type=”Number” integer=”true” />
throw Error.invalidOperation();
$AA.FadeEffect.prototype = {
FadeIn : 0,
FadeOut : 1
$AA.FadeEffect.registerEnum(“AjaxControlToolkit.Animation.FadeEffect”, false);

You can use this enumeration in this way: