r/programminghelp • • 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

3 comments sorted by

View all comments

1

u/amoliski Aug 03 '20
  if (typeof num === 'number') {
    return num - num === 0;
  }

There's a few 'Numbers' in javascript that aren't actually number numbers, like Infinity or NaN:

typeof Infinity === 'number' or typeof 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.

  if (typeof num === 'string' && num.trim() !== '') {
    return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  }

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.isFinite function, but they do have window.isFinite, so the Number.isFinite ? ... : ... is just saying that if Number.isFinite is avaliable, use it.

​

From MDN:

isFinite(Infinity);  // false
isFinite(NaN);       // false
isFinite(-Infinity); // false

isFinite(0);         // true
isFinite(2e64);      // true
isFinite(910);       // true

isFinite(null);      // true, would've been false with the 
                     // more robust Number.isFinite(null)

isFinite('0');       // true, would've been false with the 
                     // more robust Number.isFinite("0")

Final piece is the +num which 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.