Some examples of using optimization for IF statements in JS

Source: Internet
Author: User

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.

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.