Search code examples
javascriptboolean-operationsfuzzy-logic

Why does JavaScript choose the larger number in non-boolean && statements?


in JavaScript, 0 && 1 evaluates to 0, which is the lower of the two. Why, then, does 0.1 && 1 evaluate to 1, which is the higher of the two? Similarly, why does 0 || 1 evaluate to 1, but 0.1 || 1 evaluate to 0.1


Solution

  • It has nothing to do with which value is larger, the operators will return the appropriate value for the spec.

    In the case of && if the first parameter is false, it will be returned. Otherwise the second is returned. In your example 0.1 && 1, 0.1 is a truth-y value so 1 is returned. You could just as easily try 100000000 && 0.1 and see that 0.1 is returned. The reason that 0 && 1 returns 0 is because 0 is false-y so, per the spec, the first value gets returned.

    Likewise, with || if the first parameter is true, it will be returned. Otherwise the second is returned.