Simply put, coercion is the conversion of one type to another type. It happens implicitly in our code and there are also many ways to explicitly coerce our types. This lesson is designed to show you both types of coercion in action.
Instructor: [0:00] Think of coercion as a conversion. It's the changing of types from primitive to primitive or object to primitive. Here we're using a template string and it has a variable inside of it with the value of 2. Ultimately, you want to return just one type, a string and assign the string value to this variable and return it. What is happening here is what it's called implicit coercion.
[0:57] I mention that you might hear to avoid implicit coercion. You'll hear this the most when working with the == and the ===. The == will try to coerce implicitly the value to just comparing first, to see if you get them into the same type. Once they're the same type, then they'll compare their values, while the === will not do any covert coercion and will compare the values by type and value.
[1:22] The feeling on one side is that you should try not to coerce your code and make everything the same type, so it's deterministic throughout. However, the other side will say that coercion is highly valuable, and it should be embraced. One thing is for certain though. It's extremely difficult to go through your code avoiding all types of implicit coercion.
[1:54] Much of that overhead will involve explicit coercion, which is shown best with our original template string example. If you wanted to avoid implicit coercion here, we'd first explicitly coerce our number into a string so that when the variable is injected into our template string, it's already a string.
It would be nice to know what are some of the pitfalls of implicit coercion - as in concrete examples of bugs.