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.
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
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 trueToNumber(true)
is 1ToPrimitive([])
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With