Using "switch" instead of "else if" for better performance
when it comes to checking text fields on forms, it is better to use "switch" because it is much faster especially in mobile applications using phonegap or jQueryMobile.
example:
if(nametxt == ""){
alert("invalid data!");
}else if(agetxt == ""){
alert("invalid data!");
}else if(txtpassword1 != txtpassword2){
alert("invalid data");
}
in this case enter into all the "else if".
switch(true){
case(nametxt == ""):
alert("invalid data!");
return false;
case(agetxt == ""):
alert("invalid data!");
return false;
case(nametxt == ""):
alert("txtpassword1 != txtpassword2");
return false;
}
in this case, once the condition is met, exits the switch.
sorry for my bad English. ;)
Written by Eduardo Pino
Related protips
2 Responses
[I think the comment system is a little broken atm, so posting this in its entirety again]
(Ignoring the logic error in the third case of the switch statement and the functional difference between the two examples)
I'm a little confused by this statement.
There /are/ cases when switch statements are executed more efficiently, but that has nothing to do with the reason given in this post (which is just flat out wrong). See http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html. However, who knows how many interpreter optimizations have been done since the time of that writing.
Having said that, switch statements are usually preferred over if/elseif to greatly improve readability. However, the efficiency difference is arguable at the very least (and that's when talking about it at the interpreter level, not logical flow).
Not to mention that he is usign return
statement in each case