Empty Array Is Falsy, Yet [] ? 0 : 1 Evaluates To 0
Solution 1:
An array is not falsy; this can be demonstrated using console.log(!![])
When doing a left vs. right comparison via the ==
operand JavaScript attempts to coerce the inputs to a common type.
With your first example of [] == false
, the following occurs:
- The right-hand side is found to be
Boolean
so it is converted to aNumber
value, resulting in the comparison being[] == 0
. - Since the left-hand side is an
Object
it is converted to a primitive; in this case aString
via[].toString()
, resulting in the comparison being"" == 0
. - Since the left-hand side is a
String
, it gets converted to anumber
value resulting in0 == 0
. - Since both sides are
Number
primitives, their values are compared, resulting in a truthy condition
With the second example of [] ? 0 : 1
, there is no right-hand value to compare to, so it simply tests if the input is truthy. The array is not undefined
, null
, 0
, ""
or NaN
, so it is treated as truthy and thus the 'true' option is returned: 0
;
To force a non-coercive comparison between two inputs you should use the ===
operand.
Ecma Standard 6th edition Entry on CoercionJS Coercion Explained
Solution 2:
adding on the above answers..
to get the true boolean value of any value you can prefix it with !!
(in this way you won't run in any coercion issues);
in your case you can do this:
console.log(!![] == false) //logs false
Solution 3:
Just to remember.
Javascript has two types of comparison operators:
Strict
===
: Checks the type as well as the valueType Converting:
==
Checks only the value.
Try these and check the results:
console.log([] === false); //prints false
console.log([] == false); //prints true
console.log(0 == false); //prints true
console.log(1 == "1") // prints true
console.log(1 === "1") //prints false
I hope It helps.
Post a Comment for "Empty Array Is Falsy, Yet [] ? 0 : 1 Evaluates To 0"