![] == false returns true

A

aoshi

Hi

Does anyone know why the following statement return true: ![] ==
false

thanks

aoshi
 
R

Richard Cornford

Does anyone know why the following statement return
true: ![] == false

It is more accurate to say that it evaluates to true, as it is an
expression and returning values is something that functions do.

The pair of square brackets (- [] -) result in the creation of an
empty Array object.

The NOT operator (- ! -) type converts its operand (the empty Array
object) into a boolean value using the language's type conversion
rules, where all objects (including Array objects) type-converted to
boolean become boolean true, and then it inverts that boolean value to
become the result of the NOT operation. Thus ! applied to any object
results in a boolean false value.

Boolean false is equal to boolean false so the result of the whole
expression is boolean true.

Richard.
 
D

Dmitry A. Soshnikov

Hi

Does anyone know why the following statement return true:  ![] ==
false

thanks

Because type conversion rules. I guess you just want to test whether
array is empty. If so (and if correct array indexes are meant) then
you can use .length property test, which should be 0 in this case.

var a = [];

if (!a.length) {
...
}

If other properties should be considerate also, you can use some
general test function which use for..in loops with checking all own
enumerable properties:

function isEmpty(object) {
for (var k in object) // if (object.hasOwnProperty(k))
return true;
return false;
}

var a = [];
a['notArrayIndex'] = 10;

a.length; // 0

if (isEmtry(a)) { // false
..
}

P.S.: if you program only for some concrete implementations (e.g.
Gecko), for the last case you can use non-standard extensions such as
__count__ (if you won't override it with your own such property):

a.length; // 0
a.__count__; 1

Dmitry.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top