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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

If we look closely at the problem statement, the difference between ([] == false) and ([] || true) is the following −

In the first case, we are using loose conditional checking, allowing type coercion to take over.

While in the second case, we are evaluating [] to its respective Boolean (truthy or falsy) which makes use of the function Boolean() instead of type coercion under the hook.

Let's now unveil the conversions that happens behind the scenes in both cases.

Case 1 − ([] == false)

According to the MDN docs if two data types say x and y are compared using the loose equality operation ( == ), then,

The boolean value will be converted to a Number using the Number() function −

So, the condition now becomes −

[] == 0// Number(false) = 0

Then if the variable of Object type will be converted to primitive value −

"" == 0

And lastly the empty string will be converted to a Number −

0 == 0

The above eventually returns true

Case 2 − ([] || true)

In this case the truthy/falsy value of [] will be checked by converting it to a boolean using the inbuilt Boolean() function. And,

Boolean([]) = true

Hence, the truthy value [] is retained.

raja
Published on 18-Sep-2020 13:13:55
Advertisements