开发者

Why does document.writeln("a" || "b") print "a" instead of "true"?

Why does document.writeln("a" || "b") print a instead of true?

document.writeln("a" && "b") prints b

document.writeln(1==1 && 1!=1) prints false

document.writeln(1!=1 &&a开发者_如何学运维mp; 'b') prints false

document.writeln(1==1 && 'b') prints b

Does it evaluate the inner portion and return the last value for &&, and the first true value for ||?


|| and && don't always return booleans. || evaluates the first argument. If it would evaluate to true, it returns that argument. Otherwise, it returns the second argument (unconditionally).

&& evaluates the first argument. If it would evaluate to true, it returns the second argument (unconditionally). Otherwise it returns the first argument.

This allows you to do some neat things like:

function foo(optionalVar) {
    var x = optionalVar || 4; 
}
foo(10); //uses 10, since it is passed in;
foo(); //uses 4, the default value, since optionalVar=undefined, which is false


Its order of operations and truth tables.

If(a OR b) : if a is true than the whole statement is true
If(a AND b): if a is true, doesnt mean that the statement is true, 
             but if b is true as well than the statement is true
|| is the same as OR
&& is the same as AND

UPDATE
So in functional programming it returns the 1st true value. a string is considered true therefore it would return the string.

Pointy pointed out:
The empty string, it should be noted, is not true. (Which is to say, of course, that it's false)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜