Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !
like image 310
Marcus Junius Brutus Avatar asked Nov 06 '15 12:11

Marcus Junius Brutus


People also ask

Is an empty array a Falsy value?

For example, in PHP, empty arrays are falsy, but in JavaScript arrays are always truthy.

Is Empty list Falsy?

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.

Is empty array Falsy value JavaScript?

Values not on the list of falsy values in JavaScript are called truthy values and include the empty array [] or the empty object {} . This means almost everything evaluates to true in JavaScript — any object and almost all primitive values, everything but the falsy values.

Is empty array true or false JS?

If the length of the object is 0, then the array is considered to be empty and the function will return TRUE. Else the array is not empty and the function will return False.


2 Answers

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 Coercion
JS Coercion Explained

like image 130
SReject Avatar answered Oct 23 '22 11:10

SReject


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
like image 34
maioman Avatar answered Oct 23 '22 11:10

maioman