4 Primitives, Coercion, and Equality
This chapter covers
- Distinguishing between JavaScript’s two representations of nothing: undefined and null
- Understanding why some JavaScript values are considered falsy
- Using symbols to provide guaranteed-unique property keys that prevent naming collisions
- Recognizing where type coercion happens automatically in arithmetic, comparisons, and logical operations
- Choosing between loose equality with its multiple conversions and strict equality that never coerces
- Preventing performance degradation from repeated type coercion in loops and sort functions
- Exploring how V8 optimizes primitives through pointer tagging for zero-allocation storage
Here’s a fun bug: a payment system starts double-charging customers because someone wrote if (!discountCode) and didn’t realize that the discountCode value '0' is interpreted by JavaScript as false. Or how about a data visualization that runs great in development but crawls in production because the API sends timestamps as strings and suddenly your sorting function is converting types on every comparison instead of just comparing numbers?
These types of bugs happen all the time. Not because developers are careless, but because JavaScript’s type system is… well, let’s say “quirky”. The same flexibility that lets you prototype quickly with no type declarations, automatic conversions, and forgiving comparisons, also sets traps that will not be noticeable until production.