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?
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?
Because string other than empty string is a truthy value that's why the first expression resolves to true
non-null/undefined/empty strings in JavaScript are true
for boolean logic purposes. In the second case, false && true is logicall false
Because "false"
isn't a boolean, it's a string. Regardless of what text that string contains and how a human may intuitively interpret the meaning of that text, it's a string like any other.
And any non-empty string is "truthy", in that when evaluated in a boolean fashion (coerced) it results in a true
value.
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