Honestly, in most cases you want to use the if chains because they're more clear to a reader. There are a few exceptions, but not many.
Often if your code is awkward, your fundamental approach is wrong. Try this:
function validate()
{
errs = [];
// ...
if (!txt.length) {
errs.push("Must have text, man!");
}
// ...
return errs.join("<BR>");
}
It bears mentioning that strings are immutable in Javascript. If you += on strings, you're creating a lot of intermediary strings, which can slow down performance.
E.G.
var msg = "Tom";
msg += ", Brad";
msg += ", Sam";
msg += ", Rick";
This ends up creating the following strings in memory:
"Tom"
"Brad"
"Sam"
"Rick"
"Tom, Brad"
"Tom, Brad, Sam"
"Tom, Brad, Sam, Rick"
Where as the following:
var msg = ["Tom", "Brad", "Sam", "Rick"];
var msg = msg.join(", ");
creates the following in memory:
"Tom"
"Brad"
"Sam"
"Rick"
"Tom, Brad, Sam, Rick"
Wouldn't make a big difference in this case, most likely, but it's good to get into the habit of creating arrays of strings and using the join method. In larger text manipulation/generation problems, it can cause a huge slowdown.
EDIT:
If the calling function needs to check for the presence or absence of errors, you can always do an if on the .length
of the returned string. If you want to be more explicit, you can always do this:
if (!errs.length) {
return null; // or false, or a constant...
}
return errs.join("<BR>");
and then add a check in your calling code (=== null
, etc.)