JavaScript == Type Coercion Table
| Expression | Result | Why? |
|---|---|---|
0 == false | true | false is coerced to 0 |
0 == "" | true | "" is coerced to 0 |
"" == false | true | Both become 0 |
"0" == false | true | "0" → 0, false → 0 |
null == undefined | true | Special rule in JS spec |
null == 0 | false | No coercion between null and numbers |
undefined == 0 | false | No coercion between undefined and numbers |
"5" == 5 | true | "5" → 5 |
true == 1 | true | true → 1 |
true == 2 | false | true → 1, 1 != 2 |
[] == "" | true | [] → "" |
[] == 0 | true | [] → "" → 0 |
[""] == 0 | true | [""] → "" → 0 |
[1] == 1 | true | [1] → "1" → 1 |
[] == false | true | [] → "" → 0, false → 0 |
[null] == 0 | true | [null] → "" → 0 |
["0"] == false | true | "0" → 0, false → 0 |
Key Takeaways
==can be confusing because it tries to convert values to a common type.nullandundefinedare only loosely equal to each other, not to anything else.- Arrays and objects are converted to primitives before comparison.
- Always prefer
===unless you really want these coercion rules.
No comments:
Post a Comment