How to define Enum in JavaScript

Everybody familiar with Enum in server side scripting language.  I was wondering if we can define Enum type in JavaScript and I found that we can define type as Enum.

Here is the syntax to define Enum.

var Status =
{

    Failed:0;
    Succeeded:1;

}

Here is example how you can use it.

function DoAction(status)
{

    switch(Number(status)){

        case Status.Failed:
             // execute some code;
             break;

       case Status.Succeeded:
           //execute some code;
           break;
     }
}

Since every variable type we define in JavaScript is as “var” you can’t really take advantage of Enum type we define here.  You can still pass any type of values to method DoAction even though parameter type is Enum.

For example,

DoAction(3);  //method call
DoAction("SomeString");

Here you can see that we can pass 3 or “SomeString” to DoAction method parameter which is not valid enum type.  If you want to display message or want to execute some code in case of invalid value you can add another switch case.

function DoAction(status)
{

   switch(Number(status)){

        case Status.Failed:
             // execute some code;
            break;

       case Status.Succeeded:
           //execute some code;
          break;
 
       case NaN:
       default:
            //if string value is passed, Number("someString") will return NaN
            //execute some code if parameter value is not valid enum type
         break;
    }

}

Hope this helps.

Posted in Microsoft Technology Tagged with:
One comment on “How to define Enum in JavaScript
  1. Mia says:

    Improbable submit! This might help a lot of folks find out about this matter.

Ads