Logical AND (&&) and OR (||) operators

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?

Answers:

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.