2

Why do logical AND comparison between an empty string and false boolean returns an empty string? and why do logical AND comparison between a string and false boolean returns false?

Example:

'' && true; --> returns ''
'string' && true --> returns true;
'' && false --> returns ''
'string' && false --> returns false;

Question is why javascript behaves this way?

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
Bala Subramanyam
  • 185
  • 1
  • 2
  • 17
  • 4
    it returns the first decision value for leaving the expression. – Nina Scholz Oct 10 '17 at 06:17
  • 1
    You'll also get the same with `0` and `NaN`. It's one of "falsy" values in JavaScript. So your logical AND returns those values being same as `false` (since `true && false` is `false`). https://developer.mozilla.org/en-US/docs/Glossary/Falsy – Walk Oct 10 '17 at 06:22

2 Answers2

8

Javascript AND(expr1 && expr2) operator works by returning the expressions based on the logic:

if expr1 is falsy
  return expr1
else
  return expr2

Falsy values include your empty string(''), null, NaN, undefined, etc. You can read more about it at https://developer.mozilla.org/en-US/docs/Glossary/Falsy.

Also for more info on boolean operators, check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators.

davidchoo12
  • 1,261
  • 15
  • 26
0

The && operator works very simply: if the first value is falsy, it returns the first value, otherwise it returns the second value.

The empty string '' is falsy, so '' && x returns '' for all x. On the other hand, 'string' is truthy, so 'string' && x returns x for all x.

jcarpenter2
  • 5,312
  • 4
  • 22
  • 49