Please login or register. Welcome to the Studio, guest!


Quick Links:


newBookmarkLockedFalling

Scorpian

Scorpian Avatar

******
[ Bracket Admin ]

2,457


April 2006
Alright, JavaScript has many ways to execute certain things. However, some of these things might need to executed if a certain condition is present, and not at all if said condition isn't. Let's say that we need to alert a box that says a new message depending on the time of day. We've already defined the time of day previous in this code, and it will say a number representing the time span. 0 will mean morning, 1 will mean afternoon, and 2 will mean evening. However, the code we used isn't perfect. It might return completely different number. If this happens, we want to let the user know there was an error.

So, how could we do this? Well, let's try an if/else statement.

if(time == 0){
alert("Good morning!");
}else if(time == 1){
alert("Good afternoon!");
}else if(time == 2){
alert("Good evening!");
}else{
alert("Error!");
}


Yes, that code works. Yes, it will show the alert boxes. Yet, it's not really efficient, is it? How can we make it more efficient? No, not with one-line conditionals. We'll use a switch/case statement.

Whoa whoa! Wtf is a switch/case statement? It's a statement that will execute certain commands depending on what the value of a specified variable or property is. This can be extremely useful when you have a varied variable like the example above. So, how's it look?

switch(variable/property){
case "value": code to be executed break;
case "value": code to be executed break;
case "value": code to be executed break;
default: code to be executed break;
}

It's very important that you must break the code after executing it. Don't forget the ending break;. Now, you might be confused as to what "default" is. It's the code to be executed if none of the above cases are true. That fits perfectly into our example. Speaking of which, let's try the example using the switch/case method.

switch(time){
case "0": alert("Good morning!"); break;
case "1": alert("Good afternoon!"); break;
case "2": alert("Good evening!"); break;
default: alert("Error!"); break;
}


See how much neater and more organized that looks as opposed to the if/else statement? It'll also load faster since it doesn't have to loop as much. Once you get the switch/case statement down, it can prove to be extremely useful, especially when working with arrays. This is just another one of those basic concepts that can save you loads of time and make a code more efficient.

I hope you learned something today. ;)


Last Edit: Nov 19, 2006 22:29:42 GMT by Scorpian
wat

newBookmarkLockedFalling