views:

62

answers:

3

Hi there,

I know that in Javascript you can do:

var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...move along";

where the variable oneOrTheOther will take on the value of the first expression if it is not null, undefined, or false. In which case it gets assigned to the value of the second statement.

However, what does the variable oneOrTheOther get assigned to when we use the logical AND operator?

var oneOrTheOther = someOtherVar && "some string";

What would happen when someOtherVar is non-false?

What would happen when someOtherVar is false?

Just learning javascript and I'm curious as to what would happen with assignment in conjunction with the AND operator.

Thanks!!

+3  A: 

Quoting Douglas Crockford1:

The && operator produces the value of its first operand if the first operand is falsy. Otherwise it produces the value of the second operand.


1 Douglas Crockford: JavaScript: The Good Parts - Page 16

Daniel Vassallo
+3  A: 

Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:

true && "foo"; // "foo"
NaN && "anything"; // NaN
0 && "anything";   // 0

Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty string, and of course false, anything else coerces to true.

CMS
Ah ok. Thanks. That makes sense as, after all, it's the reverse of the OR operator.
Alex
A: 

&& is sometimes called a guard operator.

variable = indicator && value

it can be used to set the value only if the indicator is truthy.

mykhal