Logical operator && and two strings in javascript
in the expression
"Cat" && "Dog"
// => "Dog"
Because you're using &&
, JavaScript is promising you that it will verify that both sides of the expression are true
. In this case, "Dog"
is the just the last evaluated thing.
To be more explicit, you could do something like
var c = "Cat" != null && "Dog" != null
It's a little bit more wordy, but this boils down to
var c = true && true
console.log(c)
// => true
If you want a simple shortcut for the boolean, use the Boolean
constructor -
var c = Boolean("Cat" && "Dog")
console.log(c)
// => true
If you just use a simple REPL or JavaScript console, you'd be able to see this output very easily.
Per one of the comments below
Using ||
, JavaScript is promising you that at least one of the sides is true
. Since "Cat" is true, it stops there and returns "Cat". This is known as Short-circuit evaluation
Answer by @naomik pretty much covers it. If you want to go deep, I suggest taking a look at the ECMAScript specification, section 11.11:
http://www.ecma-international.org/ecma-262/5.1/#sec-11.11
In the "Semantics" section, we can see:
The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:
- Let lref be the result of evaluating LogicalANDExpression.
- Let lval be GetValue(lref).
- If ToBoolean(lval) is false, return lval.
- Let rref be the result of evaluating BitwiseORExpression.
- Return GetValue(rref).
I think this is because of nature of logical operator &&. Javascript executes expression "cat" && "Dog"
in following way:
Checks the value "cat" - it returns something else than "", 0, null, undefined or false and is truthy. Javascript sees &&
and so it continues expression and faces string "Dog", which is something else than "", 0, null, undefined or false and is truthy, expression ends and expression returns the last value it checked.
If you replace &&
with ||
expressions ends at first truthy value and thats way
var boolean = "cat" || "dog"
returns first value: cat