Skip to content Skip to sidebar Skip to footer

Empty Array Is Falsy, Yet [] ? 0 : 1 Evaluates To 0

If the empty array [] is falsy in JavaScript then why, when used as the predicate in the ternary operator, the operator evals to the first option? console.log([] == false); // prin

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:

  1. The right-hand side is found to be Boolean so it is converted to a Number value, resulting in the comparison being [] == 0.
  2. Since the left-hand side is an Object it is converted to a primitive; in this case a String via [].toString(), resulting in the comparison being "" == 0.
  3. Since the left-hand side is a String, it gets converted to a number value resulting in 0 == 0.
  4. 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:

  1. Strict ===: Checks the type as well as the value

  2. Type 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"