While using the Boolean() native function is Kyle’s preference, many developers will use a double negate (!!) to perform Boolean coercion. Kyle explains how this works and demonstrates a few other types of explicit coercion.
(bamboo flute music)…- What about going from anything to a boolean?…This happens a lot.…This was where the land mines were…that I talked about earlier…'cause there's a lot of ways…where we think it's happening and it's not.…We're gonna talk about ways to force it to happen.…If I start out with string one, two, three,…and I try and make that into a boolean,…I can call the boolean function,…which explicitly turns it into a boolean.…Line two, no question, it's explicit.…And if I were voting in favor of explicitness,…I'd vote for line two every time.…
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