简体   繁体   中英

Javascript logical operator && in statements?

I've starting to dig my teeth into backbone and when working with a router function creating and destroying views I came across this little snippet, which didn't quite make sense to me as I've always assumed these sorts of operators only work in conditional statements,

this.view && this.view.remove();

It was inside of a method attached to the router which seems to work like a charm, but I'm always weary of voodoo code that doesn't sit well with me.

Heres the full method

loadView : function(view) {
        this.view && this.view.remove();
        this.view = view;
    }

Would love to understand this a bit better, hope its not too silly to ask.

Cheers.

In JavaScript:

this.view && this.view.remove();

is equivalent to

this.view ? this.view.remove() : this.view;

The righthand side is only executed if the lefthand side is truthy . If the value of the expression is ignored and the lefthand side has no side-effects (as in this case), then it's also equivalent to this:

if (this.view) {
    this.view.remove();
}

So, in this specific case if there is an existing view , then it is removed. Note that the value of this expression is not necessarily a boolean (unlike in many other languages); it's whatever is returned by remove . However, this value is ignored, so it's not actually pertinent.

The operator && in javascript evaluates the first expression, if it is falsy it is returned, if it is truthy the second expression is evaluated and returned.

For || it is the other way round: the first expression is evaluated, if it is truthy it is returned, else the second expression is evaluated and returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM