While working with booleans in javascript, I have noticed an uncertainty:
"false" && true //this gives output true
false && true //this gives output false
Can I somebody explain this behaviour?
There's nothing unusual about it. The &&
operator is short-circuited logical AND. Both conditions need to be true
for the entire expression to be true
and if any condition is false
, the entire operation is false
and the rest of the conditions are not tested.
In the first example, "false"
is not the Boolean false
, it's the String "false"
, which is a valid "something", or a "truthy" value, so it evaluates to true
.
console.log("false" && true); //this gives output true
In the second example, the actual Boolean false
is used, which (as stated) causes the entire operation to be false.
console.log(false && true); //this gives output false