Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 772
Trevor Burnham Avatar asked Apr 14 '11 20:04

Trevor Burnham


People also ask

Why would you use === instead of ==?

Use === if you want to compare couple of things in JavaScript, it's called strict equality, it means this will return true if only both type and value are the same, so there wouldn't be any unwanted type correction for you, if you using == , you basically don't care about the type and in many cases you could face ...

What is the difference between == and === operators?

The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.

Which of the following is true about == and === operators?

== converts the variable values to the same type before performing comparison. This is called type coercion. === does not do any type conversion (coercion) and returns true only if both values and types are identical for the two variables being compared.

Should I use == or === in JavaScript?

== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. Checks the equality of two operands without considering their type. Compares equality of two operands with their types.


2 Answers

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

window == document; // true document == window; // false 
like image 183
Jason LeBrun Avatar answered Sep 22 '22 15:09

Jason LeBrun


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.
like image 41
SLaks Avatar answered Sep 21 '22 15:09

SLaks