JavaScript Equality Operators: When to Use == and ===
Table of contents
In JavaScript, ==
and ===
are both used for comparison, but they work differently:
==
(Equality Operator):
The
==
operator compares two values for equality after converting both values to a common type. This is known as "type coercion."If the values being compared are of different types, JavaScript attempts to convert them to the same type before making the comparison.
Example:
5 == '5' // true, because '5' is coerced to 5 before comparison
===
(Strict Equality Operator):
The
===
operator compares both the value and the type without performing any type conversion.If the values are of different types, the comparison returns
false
.Example:
5 === '5' // false, because 5 is a number and '5' is a string
In summary:
Use
==
when you want to compare values after type conversion.Use
===
when you want to compare both value and type, ensuring that no type conversion occurs.
Subscribe to my newsletter
Read articles from priyanka chaudhari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
priyanka chaudhari
priyanka chaudhari
i am a full stack web developer and i write code....