First, use the common ternary operator
if (foo) bar (); else Baz (); ==> Foo?bar (): Baz ();
if (!foo) bar (); else Baz (); ==> Foo?baz (): Bar ();
if (foo) return bar (); else return Baz (); ==> return Foo?bar (): Baz ();
For the above use ternary operator to optimize the IF statement you are certainly not unfamiliar, perhaps you often use it.
II. Use and (&&) and OR (| |) Operator
if (foo) bar (); ==> Foo&&bar ();
if (!foo) bar (); ==> foo| | Bar ();
To be honest, I didn't write the code like this, but I didn't expect it to happen in JS.
Three, omit curly braces {}
if (foo) return bar (); else something (); ==> {if (foo) return bar (); something ()}
You and I are familiar with this type of writing, but I suggest doing it in code optimization, or handing it over to Uglifyjs to help you solve it. After all, less than a curly brace, the code is not very readable.
Writing here, I think of a way to get HTML element properties.
function GetAttr (el, Attrname) {
var attr = {' for ': ' Htmlfor ', ' class ': ' ClassName '}[attrname] | | Attrname;
};
If we do not write this, we may need to use two if statements for processing, and the above code is not only simple and effective, but also strong readability.
To think about it, we can all find an effective way to solve the problem, but the key is whether we find a better way by heart.