AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |
Back to Blog
You can polyfill Number.isNaN() using the below function: Number. On the other hand, Number.isNaN(x) returns false if x is not of type number. For example: Number( null) // 0 Number( '') // 0 Number( ' ') // 0 Number( false) // 0 Number() // false It converts a lot of surprising values to 0. Unfortunately, Number(x) is more lax when it comes to whitespace, null, and other edge cases. You might mistakenly assume this means Number(x) is safer and more strict. parseFloat() is more permissive when it comes to accepting different strings: Number( '42 fail') // NaN parseFloat( '42 fail') // 42 parseInt( '42 fail') // 42 Number( ' 10') // 10 parseFloat( ' 10') // 10 parseInt( ' 10') // 10 Number(x) and parseFloat(x) handle edge cases very differently. ![]() +( ' ') // 0 What's Wrong With Number(x)? The JavaScript language spec states that +x is equivalent to Number(x). Many developers use +x to convert a string to a number. You can also use a tool like archetype that handles some of these edge cases for you: archetype.to( '42', 'number') // 42 Number( '') // 0 Using Number(x) has several edge cases that may be correct depending on your perspective. typeof parseFloat( '42') // 'number' Number.isNaN( Number( '42')) // false typeof parseFloat( 'fail') // 'number' Number.isNaN( Number( 'fail')) // true You should not use the global isNaN() function. You should always use Number.isNaN() to check if the conversion failed. ![]() Do not use 3 ways for simple operation, basing on value type assumptions, like 'here I convert definitely number to string and here definitely boolean to string'. The TLDR is you should use to convert generic JavaScript values to numbers if you want to be permissive, or parseFloat(x) if you want to be more strict. The only valid solution for almost all possible existing and future cases (input is number, null, undefined, Symbol, anything else) is String (x). I'll also describe how to enforce these rules with eslint. ![]() In this article, I'll cover the tradeoffs of parseFloat() vs Number() and Number.isNaN() vs isNaN(). With NaN, implicit radixes, and numbers vs Numbers, there are a lot of ways to shoot yourself in the foot. Converting a string to a number in JavaScript is surprisingly subtle.
0 Comments
Read More
Leave a Reply. |