Reputation: 1224
I have been using MDN Docs - Logical Operators as a frame of reference to understand the logical AND operator.
I have understood most of these code examples especially the first 4 as shown here:
a1=true && true // t && t returns true
a2=true && false // t && f returns false
a3=false && true // f && t returns false
a4=false && (3 == 4) // f && f returns false
a5="Cat" && "Dog" // t && t returns Dog
a6=false && "Cat" // f && t returns false
a7="Cat" && false // t && f returns false
However I am having issue understanding a5
, a6
and a7
.
I am failing to understand how the two strings a5="Cat" && "Dog"
are evaluating to true && true returns Dog
I am also failing to understand why the string "Cat" is evaluating to true as part of a6=false && "Cat" // f && t returns false
Upvotes: 2
Views: 86
Reputation: 10696
First of all lets look at a5:
a5="Cat" && "Dog"
Which returns dog
, the mdn-docs states that AND(&&):
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
Since a non-empty string can't be converted to false, it will return dog
, if you change the order of dog
and cat
, it will ofcourse return cat
.
In a6 false, is false and thus it returns false
because of this:
Returns expr1 if it can be converted to false...
In a7 cat
is true and thus it goes on to the next expression which is false, and thus returns false.
...otherwise, returns expr2
Upvotes: 2
Reputation: 145478
In a && b
sentence a
is evaluated first, and if a
is true
, then b
is evaluated.
(a5 = "Cat")
returns "Cat"
which is true
(only empty strings are false
), so Dog
is returned.(a6 = false)
returns false
, so the second "Cat"
part is not evaluated.(a7 = "Cat")
is true
, so the second false
part is returned.Upvotes: 0
Reputation: 414086
All non-empty strings are true
when evaluated as boolean values.
In a6=false && "Cat"
the string "Cat" is not evaluated at all, as the left side is false
.
Upvotes: 3