I. Use common ternary Operators
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 ();
You are certainly not familiar with the above use of the ternary operator to optimize the if statement. Maybe you often use it.
2. Use the and (&) and or (|) Operators
If (foo) bar () ;=> foo & bar ();
If (! Foo) bar () ;=> foo | bar ();
Honestly, I did not write code like this, but I did not expect to implement it in js.
3. Omit braces {}
If (foo) return bar (); else something () ;=>{ if (foo) return bar (); something ()}
You are familiar with this writing method, but I suggest you do it during code optimization or hand it over to UglifyJS to help you solve it. After all, there is one less braces, and the code is not highly readable.
Here, I think of a method to get the attributes of HTML elements.
Function getAttr (el, attrName ){
Var attr = {'for': 'htmlfor ', 'class': 'classname'} [attrName] | attrName;
};
If we do not write this way, we may need to use two if statements for processing. The above code is not only concise and effective, but also highly readable.
Think about it. In some cases, we can find an effective way to solve the problem, but the key is whether we try to find a better way.