Loose Equality (==)
In short: == converts values before comparing them, and its
conversion rules are one of the language's most famous sources of
surprise. When the types already match, == behaves exactly like ===.
When they differ, it slides values towards a number: a boolean becomes 0
or 1, a string becomes a number, an object becomes a primitive first. The
one exception is null and undefined: they equal each other and
nothing else, with no conversion at all. Most style guides say: default
to ===, and keep == only for the one useful idiom value == null.
![[] == false traced in four steps: false → 0, giving [] == 0; the empty array converts to "" giving "" == 0; "" converts to 0 giving 0 == 0 → true — with a note that an empty array "equals" false even though [] is truthy in an if, and that null/undefined are never converted](/api/assets/javascript/assets/0aac8176de8d4a49.png)
Compare a form value to a number
A value read from a search box or URL arrives as a string, even when it looks numeric:
"2" == 2 is true — the string converts to the number 2 first. null == undefined is true by the special rule that exempts them from
conversion. But null == 0 is false: null is never converted to a
number, so it only ever matches undefined (and itself) under ==. And
"true" == true is false — true becomes the number 1, but the string
"true" converts to NaN, which equals nothing.
Trace an empty array against false
An object meets ==, and the object is converted to a primitive before the
usual number rules apply — which produces one of the language's strangest
results:
This is true. Step by step: false becomes 0 (rule for booleans), the
empty array becomes "" (arrays convert to their items joined by commas —
an empty array joins to nothing), then "" becomes 0, and 0 == 0 is
true. Yet inside an if, [] is truthy — if ([]) { ... } runs its
block. == and truthiness follow completely different rules, and this is
exactly why they can disagree.
Boolean first
falsebecomes 0. Now:[] == 0.
Quick practice
What is "5" == 5?
What is null == 0?
What is "" == 0?
What is "true" == true?
What is [] == false?
🎯 Your turn
Trace "0" == false step by step and explain the result. Then explain why
if ("0") still runs its block, and what that says about using ==.
Write your explanation and submit it — there's no code to run here, just your reasoning.
