Why? [] not true?

I just played with nodejs and chrome nodes when I tested this:

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

How did it happen? Is that not so?

+5
source share
3 answers

See the ECMAScript standard :

11.4.9 Logical operator NOT (!)

Derivative UnaryExpression: ! UnaryExpression is rated as follows:

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

9.2 ToBoolean

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

  • undefined → false
  • null → false
  • Boolean → ( ).
  • → , +0, -0 NaN; .
  • , ( ); .
  • → true

- .

+7

, JS.


[] - , false:
[] == true
false == true


, not ing, false:
![] == true
false == true

boolean([]) true.


, not ing, !false:
!![] == true
!false == true
true == true


, :
"1" == true
true == true

"1" === true
false
+2

[] == trueis false because []it is not equal true, just as "some string"it is not equal true.

![] == trueis false because it []evaluates the true value when used in a conditional expression:

if([]) console.log('[]');
if(![]) console.log('![]');
// the result will be '[]' because [] will evaluate to true
// in a conditional even though it doesn't equal true

Another thing that can help you ![] == falseis true.

!![] == truetrue because it !!converts something into true or false meaning, based on whether it will be true or false in a conditional expression. Thus, if(obj)they if(!!obj)will always have the same result.

0
source

All Articles