Just like the toString function, the toNumber function will convert one value to another. In this case, the conversion is to a number. While number conversions are fairly straight forward, Kyle covers some issues that can lead to larger pitfalls. He also drills a little deeper into how the toNumber coercion is performed behind the scenes.
(oriental riff)…- What about ToNumber?…Obviously, it's taking any value…and making it into a number.…There's a much smaller subset of values…that make sense to go to number,…but we're gonna look at what some of these are.…So, the first set that I can show you,…can observe things like the empty string…becomes a regular zero, quote zero becomes zero,…negative zero as a string becomes the negative zero number.…That's an interesting non-symmetry,…that quote negative zero becomes negative zero,…but negative zero becomes quote zero.…
So it's not, as they say isomorphic.…It's not gonna go the same way in both directions.…Trailing white space, leading white space,…those are all stripped off.…All that's left there if there's any leading zeros…those are stripped off and we just convert to nine.…Interesting that that quote with a zero in the leading spot,…it's not taken to be an octal number.…The way a lot of people think that…oh zero in front of a number is octal.…The number function doesn't treat that as an octal,…just treats it as ignorable leading zeros.…
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