6

In my code I assumed the following || short-circuiting was safe:

var $holidayExpandBarOrOpeningHours = 
                $(".expandBar + .holidayHours_c").prev() || $(".openingHours"); 

But to my surprise if we short-circuit an empty array with a true statement an empty array is still returned. I will demonstrate with some console code below and my question is why [] || true evaluates to [].

false || "expected"
"expected"
false == []
true
[] || "expected"
[]
typeof([])
"object"
({}) || "expected"
Object {}
({}) == false
false
{} == false
SyntaxError: Unexpected token ==

Part of me thinks that it is because an array is an object which evaluates to true, however if that was the case than based on ({}) == true one would expect [] == true.

Last thing I would like to note is the outcome is the same when using use 'strict' mode.

Daniel Sokolowski
  • 11,982
  • 4
  • 69
  • 55

3 Answers3

6

When converted to a boolean value, [] is true.

> !![]
true
> ![]
false

When converted to a number, [] is 0. That's why comparing it with false returns true: when comparing two values of different types, JavaScript first converts both to numbers and then compares the numbers.

> +[]
0
> +false
0
> +[] == +false
true
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • I'm having a hard time tracking down *why* the array (`x`) is converted to a number in the `==`. As far as I can tell that will be the result of `ToPrimitive([]) == ToNumber(true)` [via rule 7, then 9, of `==`] - so then `ToPrimitive([]) == 0` (possibly by another pass)? But I can't back that up. – user2864740 Dec 18 '13 at 21:56
  • 1
    @user2864740 ToPrimitive(`[]`) yields the empty string, *then* step 5 kicks in (x is string, y is number), and the empty sting is converted to `0`, via ToNumber. (Step 5 because: the boolean turned to a number in step 7 and the array turned to a string in step 9.) – apsillers Dec 18 '13 at 22:02
  • @apsillers Thanks, just found that out too! :) – user2864740 Dec 18 '13 at 22:05
4

This is because || and use == different rules for the conversion.

The logical-or uses ToBoolean while the equality equals uses ToNumber/ToPrimitive.


From 11.11 Binary Logical Operators:

3) If ToBoolean(lval) is true, return lval.

Since ToBoolean([]) is true, [] || x results in []. This is also why if([]) { /* this runs */ }: arrays in JavaScript are "truthy" values.

From 11.9.3 The Abstract Equality Comparison Algorithm:

7) If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

9) [..then] If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.

5) [..then] If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.

The logic applied to [] == true is ToNumber(ToPrimitive([])) == ToNumber(true).


And the conversion values:

  • ToBoolean([]) is true
  • ToNumber(true) is 1
  • ToPrimitive([]) is an empty string (from DefaultValue/toString)

So:

ToNumber(ToPrimitive([])) == ToNumber(true)
ToNumber("") == 1
0 == 1
false

(Which is a long way to say what John Kugelman said.)


Also, ({}) == true is normally false and follows the same conversions as above.

Under a default environment, ToPrimtive({}) returns a non-empty string (i.e. "[object Object]" as per Object.prototype.toString). This string will evaluate to NaN after ToNumber such that NaN == 1; or false.

See Why an empty Array type-converts to zero? +[] for more details on the ToPrimitive conversion.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
3

An empty array is an object; objects coerced to booleans are true. So

({}) || true; // -> {}
[] || true; // -> []
"" || true; // -> true (empty strings are coerced to false)

Sidenote - the parentheses around {} are required to avoid parsing it as a block.

nrabinowitz
  • 55,314
  • 10
  • 149
  • 165