lucasarruda
lucasarruda

Reputation: 1482

In Javascript, is A == !B always the same as A != B

Refactoring some old code, I found the following:

someVar == !otherVar

That doesn't look that legible, I thought that could be written as:

someVar != otherVar

It seems logic to do so. But, since this is Javascript, I'm afraid of collateral problems, so is this really ok?

Upvotes: 3

Views: 106

Answers (2)

Me.Name
Me.Name

Reputation: 12544

Actually the statements in themselves are very different. !aVar will force that var into a boolean value. e.g. '!0' = true, '!1' or any other number will be false. Some other examples !'' = true !'abc = false.

!= does a lenient (in)equality comparisson, which depending on type conversions can have very different results.

e.g.

5 != 6 //true
5 == !6 //false -> !6 is forced to a boolean (6=true,!6 = false), for the comparisson 5 is cast to a boolean (true), so the comparisson nets false
5 != 5 //false
5 == !5 //false, but because the same reason as above !5 becomes true, etc.

Probably the old code you mentioned uses this exactly for the reason of boolifying the otherVar. If someVar already is a boolean, it would make sense to do so. For all other comparissons it would probably give the wrong results.

Upvotes: 5

Azamantes
Azamantes

Reputation: 1451

The answer is no.

Infinity == !NaN; // false
Infinity != NaN; // true

'abc' == !false; //false
'abc' != false; // true

Open up a console and check it for yourself. There are many more examples.

Upvotes: 6

Related Questions