Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how come ![] is not true?

Tags:

javascript

Was just playing around with nodejs and chrome's console when I tested this:

[] == true // false
![] == true // false
!![] == true // true

How come? Isn't it wrong?

like image 921
Hugo Mota Avatar asked Jun 14 '12 02:06

Hugo Mota


People also ask

Why [] === [] is false?

Because == (and === ) test to see if two objects are the same object and not if they are identical objects.

Why is [] == [] false in JS?

The reason for [] == false even though [] is truthy is: the comparison [] == false compares the value of [] to false . And to get the value of [] , the JavaScript engine first calls []. toString() . That results in "" , and that is what's actually compared to false .

Why [] == ![] Is true in JS?

Double equals, == , performs an amount of type coercion on values before attempting to check for equality. So arr == arr returns true as you'd expect as what you are actually checking is if [] == [] and both sides of the equation are of the same type.

Is false == false true?

False == (False or True) In this expression python would first solve the comparison operator in bracket. => (False or True) is said to be True. Because the 'OR' operator search for the first truthy value, and if found it returns the value else 'False'. Now we have: =>False == True is False.


1 Answers

See the ECMAScript standard:

11.4.9 Logical NOT Operator ( ! )

The production UnaryExpression : ! UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Let oldValue be ToBoolean(GetValue(expr)).
  3. If oldValue is true, return false.
  4. Return true.

9.2 ToBoolean

The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:

  • undefined → false
  • null → false
  • Boolean → The result equals the input argument (no conversion).
  • Number → The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
  • The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
  • Object → true

An array is an Object.

like image 147
kay Avatar answered Oct 31 '22 17:10

kay