Differences Between JavaScript == and === – Loose Equality vs. Strict Equality

What happened

I believe everyone is aware that JavaScript is a weakly typed language. However, do you know the differences between the “==” and “===” operators?

Loose Equality vs. Strict Equality

== Loose Equality

While we commonly use the equality operator for comparisons, it’s essential to understand that it involves type conversion in subsequent evaluations.

For example,

1==true
1=='1'


In such cases, everyone will notice that these expressions all evaluate to true.

At this point, let’s take a closer look at the types.

The three types are actually different from one another, but with the “==” operator (loose equality), they are converted to the same type before comparison.

Both boolean and string types are converted to numbers for the comparison. The provided link offers a comprehensive explanation of the conversion process ⬇

=== Strict Equality

Understanding loose equality makes it easier to grasp strict equality – it simply doesn’t perform any type coercion. Whatever type you are is the type that is compared.

1===true
1==='1'

In simple terms, using strict equality (===) will give you false for the same examples because it doesn’t convert types – they must match exactly.

Choosing Between Loose and Strict Equality

When dealing with known input types, both loose equality (==) and strict equality (===) operators can be applicable. The choice between them depends on whether simple type coercion is needed (use ==) or if a precise match without type conversion is required (use ===).

In scenarios where multiple types need to be taken into account, it is advisable to opt for strict equality (===) to prevent confusion. While the flexibility of the loose equality (==) can be advantageous, it may introduce potential pitfalls, such as non-intuitive behavior when addressing certain issues, possibly overlooking type disparities.


Conclusion

I’ve been wanting to write this article for a long time, but it’s been put off repeatedly.

It all started with debugging, trying to identify issues with the double equal (==) operator, only to struggle in finding the root cause. It wasn’t until later that I discovered the inconsistency in types, which is the drawback discussed in this piece.

Reference

💔 The entire article was written independently. Feel free to quote or reference, but please avoid copying the entire content.

🧡You can support our team by sharing the post or clicking some ads, Thanks a lot

If you have any problem about this post, please feel free to ask~

Some Random notes

Leave a Reply

Your email address will not be published. Required fields are marked *