UglifyJS is a tool for compressing and beautifying javascript. In its documentation, I see several methods for optimizing if statements. Although I haven't used it for some trial tests, I can see from here that it has done some beautification work on js. Some people may think that the if statement is so simple and can be optimized to what extent? But if you look at the following methods, you may change your mind.
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 didn't write code like this. I saw it when I learned "laruence's Linux house dish", but I didn't 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 for getting HTML element attributes in "proficient JavaScript" by the father of jQuery.
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.
For more articles about How to Write optimization code for the if statement in js, refer to PHP!