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?
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?
&&
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.
Try this:
var vehicle = !!(data.vehicles && data.vehicles.length > 0 && data.vehicles[0]);
Hope this explanation help you: basic_truthy_falsy