If ([] == false) is true, why does ([] || true) result in []?

Did just some testing and I found it odd:

[] == false

      

Yields true, it makes sense because double equal only compares the content, not the type, and tries to do type coercion. But if its content comparison and returns true, that means [] is false (if you did [] == true

, you were wrong too), which means:

[] || false

      

Should give false, but does it give [] making it true? Why?

Another example:

"\n  " == 0

      

Gives true but "\n " || false

gives "\n "

? Is there an explanation for this or is it just weird.

When I tried this in C, we get:

int x = "\n " == 0;
printf("%d\n", x);

int y = "\n " || 0;
printf("%d\n", y);

      

Outputs:

0
1

      

It makes sense, but given the impact of C on Javascript, the behavior is different.

+3


source to share


3 answers


Type conversions are not associated with false and legal values.

What is true and what is false is determined by the function ToBoolean

defined in the specifications and is []

indeed true.

On the other hand, it [] == false

returns true

because of the type conversion that occurs during expression evaluation.

The type conversion rules say that for x == y

If type (y) is boolean, return the result of the comparison x == ToNumber (y).



ToNumber

results in 0 for false, so we're left with an estimate [] == 0

. According to the same rules

If Type (x) is Object and Type (y) is either a string or a number, return the result of the comparison ToPrimitive (x) == y.

ToPrimitive

results in an empty line. Now we have "" == 0

. Back to our type conversion rules

If Type (x) is String and Type (y) is Number, returns the result of the comparison ToNumber (x) == y.

ToNumber

results in 0 for ""

, so the final score 0 == 0

is this true

!

+3


source


"Is false" (even with coercion) is different from "evaluates to false in boolean context". obj == false

asks if an object is a boolean value false

, rather than whether it will evaluate as such if evaluated in a boolean context.

You can evaluate an object in a boolean context with (!!obj)

.



[] == false;         // true
(!![]) == false;     // false

"\n  " == false;     // true
(!!"\n  ") == false; // false

      

+3


source


from ECMA-262 5.1 (p. 83):

If ToBoolean (lval) is true, return lval

[] || false; // []

      

0


source







All Articles