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?
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?
See the ECMAScript standard:
11.4.9 Logical NOT Operator ( ! )
The production UnaryExpression : ! UnaryExpression is evaluated 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 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.
It has to do with how the browser handles implicit conversions in JS.
[] is an empty array, it evaluates to false:
[] == true
false == true
noting it, will turn the object into a boolean with a value of false:
![] == true
false == true
However, boolean([]) will return true.
noting that, will turn it into a boolean with the value of !false:
!![] == true
!false == true
true == true
"1" == true
true == true
"1" === true
false
[] == true is false because [] is not equal to true, just like "some string" is also not equal to true.
![] == true is false because [] evaluates to a true value when used in a conditional statement:
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 may help you to think about it is ![] == false will be true.
!![] == true is true because !! converts anything to a true or false value based on whether it would be true or false in a conditional statement. So if(obj) and if(!!obj) will always have the same result.