Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>Often if your code is awkward, your fundamental approach is wrong. Try this:</p> <pre><code>function validate() { errs = []; // ... if (!txt.length) { errs.push("Must have text, man!"); } // ... return errs.join("&lt;BR&gt;"); } </code></pre> <p>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.</p> <p>E.G.</p> <pre><code>var msg = "Tom"; msg += ", Brad"; msg += ", Sam"; msg += ", Rick"; </code></pre> <p>This ends up creating the following strings in memory:</p> <pre><code>"Tom" "Brad" "Sam" "Rick" "Tom, Brad" "Tom, Brad, Sam" "Tom, Brad, Sam, Rick" </code></pre> <p>Where as the following:</p> <pre><code>var msg = ["Tom", "Brad", "Sam", "Rick"]; var msg = msg.join(", "); </code></pre> <p>creates the following in memory:</p> <pre><code>"Tom" "Brad" "Sam" "Rick" "Tom, Brad, Sam, Rick" </code></pre> <p>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.</p> <p>EDIT:</p> <p>If the calling function needs to check for the presence or absence of errors, you can always do an if on the <code>.length</code> of the returned string. If you want to be more explicit, you can always do this:</p> <pre><code>if (!errs.length) { return null; // or false, or a constant... } return errs.join("&lt;BR&gt;"); </code></pre> <p>and then add a check in your calling code (<code>=== null</code>, etc.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload