Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 && '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 ||?

like image 557
Shawn Avatar asked Mar 22 '11 18:03

Shawn


2 Answers

|| 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
like image 89
Claudiu Avatar answered Sep 28 '22 21:09

Claudiu


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)

like image 21
Naftali Avatar answered Sep 28 '22 22:09

Naftali