Is JavaScript's double equals (==) always symmetric?
Asked Answered
C

3

37

There are many cases in which JavaScript's type-coercing equality operator is not transitive. For example, see "JavaScript equality transitivity is weird."

However, are there any cases in which == isn't symmetric? That is, where a == b is true and b == a is false?

Caravette answered 14/4, 2011 at 20:44 Comment(0)
W
30

In Javascript, == is always symmetric.

The spec says:

NOTE 2 The equality operators maintain the following invariants:

  • A != B is equivalent to !(A == B).
  • A == B is equivalent to B == A, except in the order of evaluation of A and B.
Wooten answered 14/4, 2011 at 20:48 Comment(3)
Shouldn't that be commutative?Fineman
@Shtééf: Maybe it should be, but it isn't. en.wikipedia.org/wiki/Symmetric_relation Relations aren't operators.Wooten
Thanks for the correction—it's been too long since I picked up that math degree!Caravette
B
37

It's supposed to be symmetric. However, there is an asymmetric case in some versions of IE:

window == document; // true
document == window; // false
Bakemeier answered 14/4, 2011 at 20:52 Comment(2)
Wow, that's amazing. Could you specify which versions of IE this occurs in?Caravette
Using IE10 on Win8.0 I see this behavior in "Browser Mode: IE8" (not in IE10, IE9, or IE7 mode).Casefy
W
30

In Javascript, == is always symmetric.

The spec says:

NOTE 2 The equality operators maintain the following invariants:

  • A != B is equivalent to !(A == B).
  • A == B is equivalent to B == A, except in the order of evaluation of A and B.
Wooten answered 14/4, 2011 at 20:48 Comment(3)
Shouldn't that be commutative?Fineman
@Shtééf: Maybe it should be, but it isn't. en.wikipedia.org/wiki/Symmetric_relation Relations aren't operators.Wooten
Thanks for the correction—it's been too long since I picked up that math degree!Caravette
T
11

The answer to your actual question (is the operator symmetric) is yes. The ECMA-262 spec explicitly states:

NOTE 2 The equality operators maintain the following invariants:

  • A != B is equivalent to !(A == B).
  • A == B is equivalent to B == A, except in the order of evaluation of A and B.
Tagliatelle answered 14/4, 2011 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.