+ 2
condition in Javascript
tuts says that you can use as many as u want if else if statement but it also says that else ends the if else conditions, so how can use severals times if else if statement please help. me
2 Answers
+ 8
if(true){}
else if(!true){}
else if(null){}
else if(0){}
else {}
+ 1
Hi Rajan
If you find that you are doing a lot of if else stements, you may want to consider a different pattern to make your code much easier to maintain. Some people use the switch statement like this:
function processUserInput(direction) {
switch (direction) {
case "left":
movePlayer("left");
break;
case "up":
movePlayer("up");
break;
case "right":
movePlayer("right");
break;
case "down":
movePlayer("down");
break;
}
}
but this is still messy if you have a lot of options.
A good pattern to use is the "dispatch table":
var optionsTable = {
left: function() { movePlayer("left"); },
up: function() { movePlayer("up"); },
right: function() { movePlayer("right"); },
down: function() { movePlayer("down"); },
}
function processUserInput(direction) {
optionsTable[direction]();
}
It uses Object properties and executes them on access.
This is nice and modular and allows you to add options with ease without having to work through if-else logic.