Strict Equality (==) Loose Equality (===) in Typescript

The Typescript has two operators for checking equality. One is == (equality operator or loose equality operator) and the other one is === (strict equality operator). Both of these operators check the value of operands for equality. But, the difference between == & === is that the == does a type conversion before checking for equality. Similarly, we have two, not equal operators != and !==

Checking Equality

Two values are equal if they are

  1. identical strings
  2. numerically equivalent numbers
  3. identical Boolean values
  4. the same object (reference types)

Example:

Both == & === returns true in the above example, becuase the types of both operand are same.

Difference between == & ===

If types are same then there is no difference between == & ===

If types are different then

== does a type conversion. It will attempt to convert them to a string, number, or boolean. before doing the comparison.

=== returns false.

Equality Operator ==

Equality Operator does not check the type of the operand. It tries to convert them to string, number, or Boolean.

In the following example, both the operands are numbers. Hence the equality operator returns true.

But, in the following code, the variable b is a string and not a number. The Typescript makes the type conversion of b from string to number and then does the comparison. Hence the result is true again.

The following code also returns true.

Strict Equality Operator ===

The strict Equality operator, returns false if the types are different.

For Example, the following code returns true because both value & type of variables are same.

While the following example, returns false, because the variable b is of type string

Notes on Equality check

NaN is not equal to anything including itself.

Negative zero equals positive zero.

null equals both null and undefined.

!= and !== Not Equal

!= & !== operators check the un equality of two operands. They return true if the operands are not equal else false. != is similar to == & !== is similar to === in their comparisons. Like ==, != also, coerce the values before comparing the operands.

Example:

Equality check on Reference Types

The objects are considered equal only if are same object.

In the example, a1 & b1 are different objects hence are not equal although they have the same values

== Vs ===. Which one to use ?

Always use === as it does not attempt to coerce the values.

== does a type coercion, the result of which is not predictable as shown in the followng examples.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top