🧠 JavaScript Type Coercion — A Question That Teaches
Source: Dev.to
Let’s talk about a JavaScript expression that looks wrong but is 100 % valid 👀
[] == ![]
At first glance, most people expect this to be false. 👉 But the result is true.
Step 1: Evaluate the logical NOT
![]
[]is an object.- All objects in JavaScript are truthy.
- Applying
!to a truthy value yieldsfalse.
The expression now becomes:
[] == false
Step 2: Loose equality (==) triggers type coercion
When one operand of == is a Boolean, JavaScript first converts the Boolean to a Number:
false → 0(andtrue → 1).
So the comparison turns into:
[] == 0
Step 3: Object‑to‑primitive conversion
When an object is compared to a primitive with ==, the default hint is used, which follows the “Number” conversion sequence:
valueOf()is called first (for arrays it returns the object itself).- Since no primitive is obtained,
toString()is called.
[].toString() // ""
Now the comparison is:
"" == 0
Step 4: Final coercion
In a string‑vs‑number comparison, the string is converted to a number:
Number("") → 0
Thus we compare:
0 == 0 // true
✅ Result: true
🔑 Key Takeaways
- JavaScript follows strict, deterministic coercion rules.
==allows implicit conversions that can be surprising.- Arrays convert to strings (
[] → ""). - Booleans convert to numbers (
false → 0,true → 1). - Knowing the rules makes this behavior predictable.
- For most production code,
===(strict equality) is recommended.
Type Coercion with the + Operator
Case 1: [] + 1
Result: "1"
+can mean numeric addition or string concatenation.- When one operand becomes a string, concatenation wins.
[] → ""(empty string).
"" + 1 // "1"
Type Coercion with the - Operator
Case 2: [] - 1
Result: -1
-is numeric‑only, so both sides are forced to numbers.[] → "" → 0.
0 - 1 // -1
🚀 Challenge (Object Comparison)
Now that we understand arrays, try these with plain objects:
{} == !{}
{} - 1
{} + 1
What do you think the output is — and why?