4

I ran across an interesting bug the other day. I was testing an array to see if it evaluated to Boolean false, however just directly evaluating it always returned true:

> !![]
  true

Okay, so basically any array I put in there will be true regardless, right? I run this in the JavaScript console just for fun:

> [] == true
  false

What is going on here?

3

1 Answer 1

3

It has to do with the The Abstract Equality Comparison Algorithm versus the algorithm used to tranform a value to a boolean.

By looking at the spec, we can see that the point number 9. is the only one that defines what should be happening when Type(left side value) is Object. However it's specifying that the right side value has to be either String or Number.

9 . If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.

Looking at [] == true:

typeof [] is 'object' so we are fine, but typeof true is not 'string' or 'number', it is 'boolean', so it fallback to the last statement, point number 10.

10 . Return false.

However !![] translates into !!Boolean([]), and since [] is a thruty value (objects are), it's the same as writing !!true, which returns true.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.