JavaScript Equality Operators: When to Use == and ===

JavaScript Equals Operators: == vs ===

JavaScript Equality Operators: When to Use == and ===

Photo by Austin Chan on Unsplash

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.