Created
August 2, 2019 08:31
-
-
Save Neophen/0a153a405a8c41c6edd854a107039db9 to your computer and use it in GitHub Desktop.
Number coercion weirdness!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let value; | |
value = Number(""); | |
console.log(value); // 0 OOPS! | |
value = Number(" \t\n"); | |
// what happens here is that toNumber strips all white space! | |
// leaving the string "" which, remember converts to 0 | |
console.log(value); // 0 OOPS! | |
value = Number(null); | |
// what happens here is that toNumber get toNumber which calls toString | |
// if value has no numeric value and to string of null is empty object | |
// which returns, you geussed it an empty string, which, remember converts to 0 | |
console.log(value); // 0 OOPS! | |
value = Number(undefined); | |
console.log(value); // NaN | |
value = Number([]); | |
// what happens here is that toNumber tries to get a toValue | |
// if value has no numeric value and it tries to get toString | |
// which in empty array case returns, you geussed it an empty string. | |
// which, remember converts to 0 | |
console.log(value); // 0 OOPS! | |
value = Number([1, 2, 3]); | |
console.log(value); // NaN | |
value = Number([null]); | |
console.log(value); // 0 OOPS! | |
value = Number([undefined]); | |
console.log(value); // 0 OOPS! | |
value = Number([{}]); | |
console.log(value); // NaN |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment