Use Type-Casting and Arrays in Place of Conditional Statements
- Monday, December 8th, 2008 -
I found a neat JavaScript tutorial about how to use type-casting and arrays instead of conditional statements.
In a nutshell it takes a basic conditional statement and does it in another way.
Same old boring conditional statement:
function doSomethingGreat(myVar) {
switch(myVar) {
case 'AmberTaylor':
alert('Amber is smart as heck!');
break;
case 'Sharpdot':
alert('Amber works for the best company in the world!');
break;
}
}
The new way:
function doSomethingGreat(myVar) { //This Creates the function and passes in the condition to test against
theEgoFunction = new Array(); //This turns the function into an Array
theEgoFunction['AmberTaylor'] = theAmberTaylor; // Selects a function for one choice to run
theEgoFunction['Sharpdot'] = theSharpdot; // Selects a function for the other choice to run
theEgoFunction[myVar](); //Now finally the fuction to execute
}
function theAmberTaylor() { //The functions to run
alert('Amber is smart as heck!');
}
function theSharpdot() { //The other function to run
alert('Amber works for the best company in the world!');
}
This code looks almost identical to Actionscript (except for the built-in JavaScript functions, and some nuances). I have been working more with Actionscript recently, but as a result you can’t help to learn JavaScript along the way.
Anyhow I didn’t write this tidbit originally, however I found it neat enough to share. It originally comes from the Webmonkey blog, check it out:
View it here: http://www.webmonkey.com/tutorial/Free_Yourself_from_Conditions_in_JavaScript?oldid=31505
