r/programminghelp • u/Josedramirez07 • Aug 01 '20
JavaScript ELI5: The is-number package in JavaScript
Anyone mind explaining the implementation? I have no idea why it works at all.
Here's the code: https://www.github.com/jonschlinkert/is-number/tree/master/index.js
4
Upvotes
1
u/amoliski Aug 03 '20
There's a few 'Numbers' in javascript that aren't actually number numbers, like
InfinityorNaN:typeof Infinity === 'number'ortypeof NaN === 'number'So if you do Infinity - Infinity, you get 'NaN' instead of 0, so by returning num - num, you are making sure that the number given to you is an actual number.
Here, we're testing a string like '6' - we check to make sure that the trimmed string (the string with spaces/tabs removed) is not an empty string, then we check to see if it's a 'finite number'
Internet Explorer and older versions of the other browsers don't have a
Number.isFinitefunction, but they do havewindow.isFinite, so theNumber.isFinite ? ... : ...is just saying that ifNumber.isFiniteis avaliable, use it.
From MDN:
Final piece is the
+numwhich is a javascript shortcut to turn a string into a number thanks to the JS type coercion.+''is 0, which is why we had to check for an empty string earlier.
So, if the value is a Number type object, make sure it's a regular number and not a special one. If it's a string, convert it to a number and pass it into isFinite. If it's not a string or a number, return false.
Why not just pass the number into isFinite instead of subtracting itself from itself? It's probably a little bit faster... maybe.