View Full Version : When to use "IF" and "CASE"
hogtied
02-17-2003, 04:32 AM
Hello fellow members,
I understand that "IF" and "CASE" is basiclly the same in which they both test conditions true or false. When would you use "IF" or "CASE". Does one have any advantages over using the other? For me I believe it only to be personal perference.
Almost like "FOR", "DO", and "DOWHILE". The diffence in these are substantial enough to consider when to use one or the other. The "IF" and "CASE" I really don't think one is better than the other.
Thanks,
Hogtied.
if (something && anotherthing || somethingelse) {
//bla
}
Seems better to me than:
switch (true) {
case (something && anotherthing || somethingelse):
//bla
break;
}
:)
Spookster
02-17-2003, 05:51 AM
It is mainly a difference of readability and code size. If you have 15 different conditions to go through then usings an IF ELSE construct would be a bit less readable and use take much code and span a few pages whereas a switch construct would be more compact and easy to read.
beetle
02-17-2003, 06:05 AM
well, generally speaking, when performing multiple conditions on a single variable, swith/case statments are easier to write. However, in most situations that you or I would use them for they would be easily mimicked by a large collection of if...else statments.
Here (http://home.earthlink.net/~kendrasg/info/js_opt/) is and interesting link about optimizing javascript code, primarily loops. One of them uses switch statments in a way not best duplicated by if...else.
glenngv
02-17-2003, 09:05 AM
"If" statements test each condition until one is satisfied, while switch statements "jumps" to the right case at once.
take this simple example:
this will test condition 1, then 2, then 3.
var i=3;
if (i==1){
}
else if (i==2){
}
else if (i==3){
}
else {
}
this will "jump" to case 3 without going to cases 1 and 2.
var i=3;
switch (i){
case 1:
break;
case 2:
break;
case 3:
break;
}
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.