Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

Conflicting boolean values of an empty JavaScript array

Can anyone explain why the following two statements both evaluate as true?

[] == false

and

!![]

This question is purely out of curiosity of why this happens and not about how to best test if an array is empty.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first one:

[] == false

The == operator does type conversion to its operands, in this case the both sides are converted to Number, the steps taken on the Abstract Equality Comparison Algorithm would be:

  • object == boolean
  • object == number
  • string == number
  • number == number

In code:

[] == false; // convert false to Number
[] == 0;     // convert [] to Primitive (toString/valueOf)
"" == 0;     // convert "" to Number
0  == 0;     // end

The second comparison, [] is converted to primitive, their valueOf and toString methods are executed, but since valueOf on Array objects, returns the object itself (is inherited from Object.prototype), then the toString method is used.

At the end as you see, both operands are converted to Number, and both yield zero, for example:

Number([]) == 0;
Number(false) == 0;

And empty array produces zero when converted to Number because its string representation is an empty string:

[].toString(); // ""

And an empty string converted to Number, yields zero:

+""; // 0

Now, the double negation (!![]) produces true because all object instances are truthy:

![];  // false, [] is truthy
!![]; // true, negation

The only values that are falsey are:

  • null
  • undefined
  • 0
  • NaN
  • "" (an empty string)
  • false

Anything else will produce true when converted to Boolean.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...