JavaScript Tutorial: Ways to optimize IF statements

Source: Internet
Author: User

UGLIFYJS is a tool for compressing and beautifying JavaScript, and in its documentation, I've seen several ways to optimize if statements. Although I have not used it to do some experimental testing, but from here I can see that it does make JS a landscaping work. Perhaps some people think that if statement is so simple, can optimize to what extent? But looking at the following ways, you may change your mind.

  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 code like this, I've seen it when I was studying "brother Bird's Linux private dish", 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 the way in which the father of jquery is getting HTML element attributes in "proficient in JavaScript."

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.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.