Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short-circuiting an empty array in JS has an unexpected outcome: `[] || true == []`

Tags:

javascript

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.

like image 857
Daniel Sokolowski Avatar asked Dec 18 '13 21:12

Daniel Sokolowski


3 Answers

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
like image 131
John Kugelman Avatar answered Oct 04 '22 08:10

John Kugelman


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.

like image 34
user2864740 Avatar answered Oct 04 '22 09:10

user2864740


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.

like image 23
nrabinowitz Avatar answered Oct 04 '22 10:10

nrabinowitz