-2

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?

Aman Kumayu
  • 381
  • 1
  • 9

4 Answers4

1

Because string other than empty string is a truthy value that's why the first expression resolves to true

Zain Zafar
  • 896
  • 7
  • 19
1

non-null/undefined/empty strings in JavaScript are true for boolean logic purposes. In the second case, false && true is logicall false

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

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.

David
  • 208,112
  • 36
  • 198
  • 279
1

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
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71