Day 9: Update on Type Coercion, ‘==’ Operators and ToPrimitive

So, between dinner and temporary job applications to finance my JavaScript ninja training, I am still stuck on the same article: ‘Truth, Equality and JavaScript’ by Angus Croll.

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).

*Note to self: Still need to understand how valueOf and toString methods convert Objects to a primitive value (Primitives are the basic JavaScript values, such as Strings, Booleans, Numbers, as well as undefined and null).

Anyway, this JavaScript Gangsta headed to watch Straight Outta Compton see, JS Gangsta-p rolling out!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s