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?

2
  • 4
    it returns the first decision value for leaving the expression. Oct 10, 2017 at 6: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). developer.mozilla.org/en-US/docs/Glossary/Falsy
    – Walk
    Oct 10, 2017 at 6:22

2 Answers 2

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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.