1

Logical AND (&&) and OR (||) operators --- who knew they could trick us like this :)

Their definition, for JS (according to this explanation), is the following:

expr1 && expr2 => Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

expr1 || expr2 => Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

Testing it, indeed it works just as the definition, but here's the problem:

false || ""  //returns ""
"" || false  //returns false

So, obviously:

(false || "") ==  ("" || false) // true

But, sadly

(false || "") === ("" || false) // false

To the main two questions:

  1. Is this a bug, or why is JavaScript forcing us to use == operator or to pay attention to the order when using && and || operators?
  2. Why is javascript unable to convert expr1 to true in this expression ("" || false)?. I mean, isn't it as simple as prepending "" with the NOT (!) operator?
Adelin
  • 7,809
  • 5
  • 37
  • 65
  • possible duplicate of [Do the && and || operators convert their operands to booleans?](http://stackoverflow.com/questions/7601962/do-the-and-operators-convert-their-operands-to-booleans) – Qantas 94 Heavy Aug 18 '14 at 08:55
  • "==" forces a type conversion. avoiding it always good – Prabhu Murthy Aug 18 '14 at 08:57
  • The answer is in the question. `expr1 || expr2 => Returns expr1 if it can be converted to true; otherwise, returns expr2`. In the last case you have `"" === false` that's false – Luca Rainone Aug 18 '14 at 08:58

1 Answers1

3

It's just how they work. It's not a bug:

Returns expr1 if it can be converted to false; otherwise, returns expr2

This means you can use "default values", like this:

function someFunc(passedParameter){
    var newValue = passedParameter || 1337
}

Or run functions when conditions are met:

var myBool = true;
myBool && someFunc(); // someFunc will only be evaluated if `myBool` is truthy

More info on truthy / falsy

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • But it states `Returns expr1 if it can be converted to false`. You can't convert `"a"` to false? Try `!"a"` to see what it does. – Adelin Aug 18 '14 at 08:59
  • 1
    `!"a"` is `true`, because `!` is a logical inversion. To convert something to a boolean, use double exclamation marks: `!!"a"`. Have a look at [what values are truthy or falsy](http://www.sitepoint.com/javascript-truthy-falsy/) – Cerbrus Aug 18 '14 at 09:00
  • This is interesting - never though of it that way. Thanks, you've clarified it all with `!!"a"` (because that's the actual conversion, I was thinking of inversion". – Adelin Aug 18 '14 at 09:11
  • Eh, whoops, that's what I meant to say, @fast o.O – Cerbrus Aug 18 '14 at 09:33