当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Why does ( true && 1 ) return 1, but ( 1 && true ) returns true?

问题描述:

In C I know true and false evaluate to 1 and 0 respectively. show in this case just prints to the screen... Not sure what's going on here. I'm expecting to get true back. This 1 is messing up my karma.

show(1 && true);

true

show(true && 1);

1

网友答案:

Simply put - that's how && is defined. In Javascript, a && b returns a if a is falsy and b if a is truthy.

Conversely a || b returns a if a is truthy and b if a is falsy.

This makes sense intuitively - if a is false in a && b, then why bother reading the rest of the expression? You already know the whole thing is false. So just return false. But Javascript makes the decision to return a, which is falsy, instead of making up the value false to return out of nowhere.

This is based on short-circuit evaluation common to all C-style languages.

It allows for much expressiveness in Javascript. For instance this pattern:

var foo = function(opts) {
    opts = opts || {}
    // ...
}

Implements an optional parameter opts. If opts is not passed in at all, opts = opts || {} will set opts to {}, so the rest of the code does not have to know opts wasn't passed.

In long-hand it is equivalent to the following:

var x = a || b; // is equivalent to
var x;
if(a) {
    x = a;
}
else {
    x = b;
}

and

var y = a && b; // is equivalent to
var y;
if(!a) {
     y = a;
}
else {
    y = b;
}

Therefore Javascript can be much more terse than C or Java, because simple if statements can be replaced by || or && entirely. Sometimes this makes the code more terse and less readable and more like Perl, other times it allows for new Javascript patterns, like opts = opts || {}.

Another use is in patterns like

var displayName = user.fullname || user.email;

Which means "use the full name if available; if not, fall back to email." I personally find this expressive and readable, but it's arguably terse and obscure depending on which part of the Javascript community you hail from. Because of examples like this, and essentially the fact that truthy values are far more diverse then falsy values, using short-circuit || is much more common than short-circuit &&, as in your question.

分享给朋友:
您可能感兴趣的文章:
随机阅读: