CodePark/ questions / Equality & copying
START PRACTICINGPRACTICE
Frontend question · JavaScript › Equality & copying

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

=== (strict equality) compares without converting types, so different types are never equal. == (loose equality) first converts both sides to a common type, then compares.

The == conversion rules cause surprises. These are all true:

  • '' == 0
  • '0' == 0
  • [] == false

Yet '' == '0' is false.

Both operators compare objects by reference. Two different objects with the same contents are not equal under either one.

Edge cases:

  • NaN is not equal to anything, not even itself, under both operators.
  • null == undefined is true. But neither is loosely equal to 0 or ''.
  • Object.is is like ===, with two differences: Object.is(NaN, NaN) is true, and Object.is(0, -0) is false.

Use === by default. The one common, intentional use of == is x == null, which checks for both null and undefined.

  • === does no type conversion. == converts types first.
  • Both compare objects by reference.
  • NaN is never equal to itself. Use Number.isNaN or Object.is to check for it.
  • null == undefined is true, but neither one equals 0.
  • Use === by default. x == null is the accepted exception.