Yurii Savchuk
Yurii Savchuk

Reputation: 13

Why Array is equal not array (javascript)?

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"?

Upvotes: 0

Views: 425

Answers (2)

Thomas
Thomas

Reputation: 12687

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

Upvotes: 2

marvel308
marvel308

Reputation: 10458

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

Upvotes: 0

Related Questions