Monday, May 25, 2026

Javascript Coercion

 

JavaScript == Type Coercion Table

ExpressionResultWhy?
0 == falsetruefalse is coerced to 0
0 == ""true"" is coerced to 0
"" == falsetrueBoth become 0
"0" == falsetrue"0" → 0, false → 0
null == undefinedtrueSpecial rule in JS spec
null == 0falseNo coercion between null and numbers
undefined == 0falseNo coercion between undefined and numbers
"5" == 5true"5" → 5
true == 1truetrue → 1
true == 2falsetrue → 1, 1 != 2
[] == ""true[] → ""
[] == 0true[] → "" → 0
[""] == 0true[""] → "" → 0
[1] == 1true[1] → "1" → 1
[] == falsetrue[] → "" → 0, false → 0
[null] == 0true[null] → "" → 0
["0"] == falsetrue"0" → 0, false → 0

Key Takeaways

  • == can be confusing because it tries to convert values to a common type.
  • null and undefined are 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