Where I Get Stuck: ToPrimitive
It’s not that it’s a bad article, but just that I’m a slow learner. I did pick up and better intuit the flow of type coercions that occur when using an ‘==’ operator. But I’m currently stuck on ToPrimitive, and particularly the valueOf and toString object methods, and how they operate in converting objects to primitives. Even the MDN resources were not particularly helpful, in my opinion. I’m currently traversing other online blog/content on these two methods to really come to grips with them, they’re my only sticking point in the otherwise relatively easy to follow flow of type coercions.
My Type Coercion Brain Gains
- if (expression) conditionals will evaluate the ‘expression‘ using ToBoolean. Angus Croll describes the type coercion flow here, which is essentially the standard truthy/falsy paradigm we’ve all likely been introduced to: null, undefined, 0, NaN and “” (empty string) resolve to false, everything else resolves to true.
- ‘==’ comparisons follow a higher order type coercion flow. The way I’ve memorised it is:
- Booleans get converted ToNumbers() (True is 1, False is 0)
- Then Objects get converted ToPrimitives (and this either by valueOf or toString object methods)
- Then Strings get converted ToNumbers() (e.g ‘12345’ becomes 12345, but ‘abcde’ becomes NaN because it can’t be converted to a numeric value).
- Once everything’s been reduced as far as possible, or is the same type, then treat ‘==’ as if it were ‘===’.
- The only exception in all this, or another rule, is null == undefined, which always resolves to true (as opposed to a strict equality operator ‘===’ which would resolve to false).