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.
Letβs break it down step by step, using JavaScriptβs actual rules β no magic, no guessing
Step 1: Evaluate the logical NOT
![]
-
[]is an object - All objects in JavaScript are truthy
- Applying
!to a truthy value results infalse
So the expression becomes:
[] == false
Step 2: Loose equality (==) triggers type coercion
In JavaScript's loose equality (==) logic, if one of the operands is a Boolean, it is always converted to a Number before the comparison continues.
The Conversion Rule
According to the ECMAScript specification, the process for [] == false (for example) looks like this:
- Boolean to Number: false becomes 0. (Conversely, true becomes 1).
- The Resulting Comparison: Now the engine is looking at [] == 0.
- Object to Primitive: Since one side is a number and the other is an object (the array), JavaScript triggers the ToPrimitive process on the array
[] == 0
Step 3: Object-to-primitive conversion
- When using the loose equality operator (==) to compare an object to a primitive, JavaScript uses the "default" hint, which almost always behaves like the Number sequence:
- valueOf() is called first. (For most plain objects and arrays, this just returns the object itself).
- toString() is called second because valueOf didn't provide a primitive.
For an empty array:
[].toString() // ""
So now the comparison becomes:
"" == 0
Step 4: Final coercion
In a string vs. number comparison, the string is converted to a number. Number("") is 0.
"" (empty string) β 0
Comparison becomes:
0 == 0
β 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
- This behavior is predictable once you know the rules
- This is exactly why === is recommended in most production code.
Type Coercion with the + Operator
πΉ Case 1: [] + 1
π Result: "1"
Why?
- + is special in JavaScript It can mean addition or string concatenation
- When one operand becomes a string, concatenation wins
- [] β "" (empty string)
Expression becomes:
"" + 1 β "1"
Type Coercion with the - Operator
πΉCase 2: [] - 1
π Result: -1
Why?
- - is numeric only
- JavaScript forces both sides to numbers
[] β "" β 0
Expression becomes:
0 - 1 β -1
π Challenge (Object Comparison)
Now that we understand arrays, hereβs a bit tougher one:
{} == !{}
{} - 1
{} + 1
Same language. Same coercion rules.
π What do you think the output is β and why?
Top comments (0)