Quantcast
Channel: Why do empty JavaScript arrays evaluate to true in conditional structures? - Stack Overflow
Viewing all articles
Browse latest Browse all 8

Answer by Abir for Why do empty JavaScript arrays evaluate to true in conditional structures?

$
0
0
[]==false  // returns true

This evaluates to true, because of the Abstract Equality Algorithm as mentioned here in the ECMA Specification #Section 11.9.3

If you run through algorithm, mentioned above.

In first iteration, the condition satisfied is,

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

Hence the above condition transforms to -> [] == 0

Now in second iteration, the condition satisfied on [] == 0:

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

[] is an object, henceforth, on converting to primitive, it transforms to an empty string ''

Hence, the above condition transforms to -> '' == 0

In third iteration, condition satisfied, is:

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

As we know, empty string, '' is a falsy value, hence transforming an empty string to number will return us a value 0.

Henceforth, our condition, will transform to -> 0 == 0

In fourth iteration, the first condition is satisfied, where the types are equal and the numbers are equal.

Henceforth, the final value of the [] == false reduces to 0 == 0 which is true.

Hope this answers your question. Otherwise, you can also refer this youtube video


Viewing all articles
Browse latest Browse all 8

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>