JavaScript Runtime Semantics

Coercion & Equality

JavaScript can convert values explicitly or implicitly. Strict equality avoids most implicit conversion, while loose equality follows a set of coercion rules that are precise but rarely obvious at a glance.
  • Coercion is conversion between runtime value types
  • === compares without type coercion
  • == is not random, but it is non-local
  • NaN and -0 require special sameness awareness
  • TypeScript does not remove coercion from runtime
Comparison tools
ToolDoes coercion?Use for
==YesRare intentional nullish checks like x == null
===No type coercionDefault equality
Object.isSameValue semanticsNaN and -0-sensitive checks
Number.isNaNNo coercionCheck actual NaN
Boolean(value)Explicit truthinessClear condition conversion
Equality examples
0 == false          // true
0 === false         // false
null == undefined   // true
null === undefined  // false
NaN === NaN         // false
Object.is(NaN, NaN) // true
Object.is(0, -0)    // false
The rules are deterministic. The question is whether the reader should have to simulate them.
Sources
  • MDN JavaScript Guide and ReferenceExpressions, operators, and equality comparisons
  • ECMAScript Language SpecificationAbstract Equality Comparison
  • You Don’t Know JS YetTypes and Grammar