Empty array is falsy, yet [] ? 0 : 1 evaluates to 0 [duplicate]

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); // prints true
console.log([] ? 0 : 1);  // prints 0 !

Answers:

Answer

First, an empty array is not falsey, to get the actual boolean value prefix it with !! such as: console.log(!![]) // true

The result you got from the first comparison is due to coercion. When doing a left vs. right comparison via the == operand JavaScript attempts to coerce the inputs to a common type, as follows:

  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 expression, there is no right-hand to compare to, so it simply tests if the input is truthy. The array is not null, undefined, 0, "" or NaN, therefore, it is truthy.

To force a non-coercive comparison between two inputs you should use the === operand.

Ecma Standard 6th edition Entry on Coercion
JS Coercion Explained

Answer

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
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.