2
var operand1 = null;
var operand2 = true;
var booleanOperatorReturnsABoolean = operand1 && operand2;
booleanOperatorReturnsABoolean == false || booleanOperatorReturnsABoolean == true

Result: false

Running this in a javascript console shows that the boolean operator (&&) sometimes may NOT result in a boolean

Jonathan
  • 6,741
  • 7
  • 52
  • 69
  • Have you looked this up? It has been brought up many times. – Anonymous Jun 08 '15 at 17:02
  • 5
    The logical AND and OR operators in JavaScript are not boolean operators. They are [short-circuit operators](https://en.wikipedia.org/wiki/Short-circuit_evaluation). – Aadit M Shah Jun 08 '15 at 17:02
  • [Do the && and || operators convert their operands to booleans?](http://stackoverflow.com/questions/7601962/do-the-and-operators-convert-their-operands-to-booleans) – Jonathan Lonowski Jun 08 '15 at 17:13
  • 1
    @AaditMShah: No, [they're _logical operators_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-Circuit_Evaluation) that _can_ short-circuit. – Cerbrus Jun 08 '15 at 17:34
  • More like *illogical* operators `null && false == false && null || new Date("February 7, 2014").toDateString() == new Date("2014-02-07").toDateString() || 0.1+0.2==0.3` – Jonathan Jun 08 '15 at 17:35
  • @JonathanLeaders: That's your opinion, but the way they work makes perfect sense. In fact, it's pretty darn convenient compared to strictly returning `true`/`false` – Cerbrus Jun 08 '15 at 17:49

1 Answers1

5

Because that's how they're designed.

&& returns the left side of the expression if it's falsy, otherwise, it returns the right side.
|| returns the left side of the expression if it's truthy, otherwise, it returns the right side.

In cases where the left side is returned, the right side isn't even evaluated, allowing you to code shortcuts like:

var hasValue = "foobar" === someVariable;
hasValue && doSomething();

Here, doSomething will only be executed if somevariable equals "foobar"

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • I see this is false `null && false == false && null || new Date("February 7, 2014").toDateString() == new Date("2014-02-07").toDateString() || 0.1+0.2==0.3` – Jonathan Jun 08 '15 at 17:23
  • @JonathanLeaders: that whole line returns `true` for me... – Cerbrus Jun 08 '15 at 17:55
  • That's exciting. I'm using mozilla's version of javascript through firefox & IE, I get `false` in the alert box here: http://jsfiddle.net/jleaders/8FAkv/3/ – Jonathan Jun 08 '15 at 19:31