Kyle defines implicit coercion as a side effect of some other operation. In other words, it’s not clear when looking at the code that coercion will occur. Kyle introduces implicit coercion with a few examples using String and Number values.
(techno music)…- So if that's explicit coercion,…let's turn our attention to implicit coercion.…Implicit coercion is something that happens…as a side effect of some other operation.…It's not clear when you look at the code…that the coercion is going to occur.…And is implicit coercion evil?…Most people say yes.…I am going to present to you the counter case,…which is I think that implicit coercion…is actually not evil.…I actually think it's quite useful…and we ought to employ more of it in our code.…
So let's look at some examples of…what implicit coercion is.…Line 2: When I say foo minus zero…and foo was a string 123,…I'm doing a minus of operation,…a minus arithmetic operation;…but minus is only defined for numbers,…which means if you give it something non-number,…it has to coerce it to a number first.…And when I subtract zero, the end result is…that I haven't changed the value;…so I end up doing a coercion implicitly…from string 123 to the number 123.…
That may, on its surface, look somewhat weird,…like why would somebody choose to do it that way?…
Note: This course was created by Frontend Masters. It was originally released on 8/29/2015. We're pleased to host this training in our library.
- Primitive types: undefined, string, number, boolean, and object
- Special values: NaN and negative zero
- Natives: Regex and date
- Functions: toString, toNumber, and toBoolean
- Implicit coercion
- Explicit coercion
- Strings, numbers, and booleans
- Operators: Double equal and triple equal