0

I have inherited some javascript which has this line:

var vehicle = data.vehicles && data.vehicles.length > 0 && data.vehicles[0];

This returns the data.vehicles[0] object, not true or false. Why?

Sam
  • 601
  • 6
  • 22

2 Answers2

1

&& and || don't return booleans exclusively. && returns the last truthy value (or the first falsey) and || returns the first truthy value or the last falsey.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • 1
    The rules table [on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators) explains it pretty well: `expr1 && expr2`, *Returns expr1 if it can be converted to false; otherwise, returns expr2.* – worc Nov 18 '15 at 21:31
  • 2
    *"`||` returns the first falsey value."* So, what does `true || false` return? – Felix Kling Nov 18 '15 at 21:31
  • @FelixKling, in that case the operator short-circuits and just returns true – worc Nov 18 '15 at 21:32
  • 2
    @worc: But `true` is not a falsey value. According to the answer, `false` should be returned. – Felix Kling Nov 18 '15 at 21:32
  • 3
    The explanation is not correct anyway. `&&` returns the left operand if it's falsy, and the right operand otherwise. `||` returns the left operand if it's truthy and the right otherwise. – Felix Kling Nov 18 '15 at 21:33
  • yeah, it should be edited, i missed the the flipped logic – worc Nov 18 '15 at 21:34
  • 1
    Apparently so did I. – cwallenpoole Nov 18 '15 at 21:37
0

Try this:

var vehicle = !!(data.vehicles && data.vehicles.length > 0 && data.vehicles[0]);

Hope this explanation help you: basic_truthy_falsy

JoMendez
  • 880
  • 9
  • 22
  • 1
    Hey thanks for your answer, I was more looking for an explanation of why it happens, not how to convert it to a bool :) – Sam Nov 18 '15 at 21:31