Using the double-equal operator can be helpful. Kyle shares some pro-tips about how to determine when this operator should be use. He also talks about the performance impacts of coercion.
(intense music)…- So let me finally make that case,…then, more explicitly about where this…implicit coercion can be helpful.…In all those places where you are doing a comparison…with a value, and you don't want…to allow coercion to help you,…you're gonna have to write code like line two.…Which is you're gonna have to triple equals a check…against each variation of the value that you wanna allow.…In this case there's two variations,…so I need two uses of the triple equals.…
I gotta say is it triple equal to the regular three,…the number three, or triple equal to the string three?…The alternative, of course, is line six.…Now, I would argue that line six is a better line…of code, it's a more reasonable, and more readable,…and more maintainable line of code because I've taken…this implementation detail of, it could be a number,…or it could be a string.…In this case I know that it'll never be one of…the problem values, so I've gotten the payoff…that now my code can take that detail,…and hide it away as an abstraction,…
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