I’m trying to write more readable and more efficient code, I’ve always hated if if if chains .. is it possible to write the following statement in some other more “elegant” way like maybe using ternary ops :
if(text.length < 1){
if(errtext.length > 1){
errtext+="<br>";
}
errors = true;
errtext += "Field cannot be empty";
}
Thank you
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:
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.
This ends up creating the following strings in memory:
Where as the following:
creates the following in memory:
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
.lengthof the returned string. If you want to be more explicit, you can always do this:and then add a check in your calling code (
=== null, etc.)