1

We all know that JavaScript is quite a funny language with tricky parts. Please, explain how it works, if possible: [ ] is equal ![ ] .

 [ ] == ![ ]    // -> true

I don't understand it, why the result is "true"?

1
  • Because array in JavaScript is an object. See Mozilla CDN Arrays Commented Aug 16, 2017 at 7:37

2 Answers 2

3

Because == doesn't compare them typesafe, but the values get casted:

[] == ![]
//is
[] == false
//is casted into
"" == false
//and that into
false == false
//wich is
true

use the typesafe comparison

console.log(`[] == ![]`, [] == ![])
console.log(`[] === ![]`, [] === ![])

in my opinion, the only reason to use == is when you chack against null or undefined and want to cover both. So, writing

value == null
//or
value != null

//instead of the more explicit (but longer)
value === null || value === undefined
//respectively
value !== null && value !== undefined

everywhere else I'd use === because of these funny results that == sometimes has.

Here's a funny little clip on that topic, enjoy: https://www.destroyallsoftware.com/talks/wat

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

2 Comments

Thomas, thanks for answers. I review some crazy examples and try to understand how they work. Now I understand this example.
@YuriiSavchuk for more info, research into truthy and falsy values.
0

When you call if (array == false) you compare values of this object and the primitive false value. Internally, arr.toString() is called, which returns an empty string "".

![] // will return false

[] == false // this would return true, since "" == false

console.log((![]).toString());
console.log(([]).toString());
console.log("" == false);

This is how it is called internally, please check out this answer for more details

1 Comment

marvel308, thanks for answers. I review some crazy examples and try to understand how they work. Now I understand this example.

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.