When == Performs Type Coercion
What you'll learn: How the loose equality operator (==) converts values to the same type before comparing them.
The Double-Equals Surprise
You learned that === checks both type and value without any conversion. The == operator, however, takes a different approach: if the two operands have different types, JavaScript attempts to convert one or both to a compatible type before comparing.
This process is called type coercion, and it happens automatically behind the scenes.
How It Works
When you use == with different types, JavaScript follows a complex set of rules to decide how to convert the values. Here are some common examples:
5 == "5" // true (string "5" converted to number 5)
true == 1 // true (true converted to 1)
false == 0 // true (false converted to 0)
null == undefined // true (special case: treated as equal)
"" == 0 // true (empty string converted to 0)
Compare this to ===:
5 === "5" // false (different types, no conversion)
true === 1 // false
null === undefined // false
Why This Matters
Type coercion can lead to unexpected results. While 5 == "5" might seem convenient, it can hide bugs where you accidentally compare different types. Most developers prefer === because it's predictable: if the types don't match, the answer is simply false.
Key Takeaway: The == operator performs type coercion, automatically converting operands to compatible types before comparing—which can produce surprising results and is why === is generally preferred for clarity and safety.