Search

Apr 2, 2009

Enum in JavaScript


We are using enum in server side scripting language, recently I come across requirement where I have to write lots of if-else if clause, then I found the interesting thing which is enum.

Lets see how we can declare enum.

var Technology = 
{
Microsoft: 0,
PHP: 1,
ROR: 2,
Java: 3
}

Minor change in declaration, now lets see how we can use enum.

function Show(tech) {

var msg = 'Welcome to the world of {0}';
switch (Number(tech)) {
case Technology.Microsoft:
alert(String.format(msg, 'Microsoft'));
break;
case Technology.PHP:
alert( String.format(msg, 'PHP') );
break;
case Technology.ROR:
alert(String.format(msg, 'ROR') );
break;
}

}


//And here is the function call
Show(0);
Show(Technology.PHP);
Show(Technology.Microsoft);
Show(2);



No comments: