20.07.2019 — JavaScript — 1 min read

Recently I have experienced the real pain of polyfilling Number.isSafeInteger method.

A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.

It happened at work; something was not working for IE 11, and there was a lot of culprit pull requests, but one in particular sparkled my attention. In this pull request, there was a line of code that was using Number.isSafeInteger.

1 return arr . filter ( Number . isSafeInteger ) ;

Nothing special, until I checked the famous browser compatibility tables of MDN web docs to confirm that my theory was real, Number.isSafeInteger is not supported in IE, oh snap.

I ran to the polyfill section, I copied out the recommended polyfill code, and I victoriously announced to my team, "I found it!".

1 Number . isSafeInteger = 2 Number . isSafeInteger || 3 function ( value ) { 4 return Number . isInteger ( value ) && Math . abs ( value ) <= Number . MAX_SAFE_INTEGER ; 5 } ;

Not that simple, it turns out that Number.isInteger was also not supported and we had no polyfill again for it. I did not want to commit the same mistake twice, so this time I double-checked the source code of the polyfill for Number.isInteger .

1 Number . isInteger = 2 Number . isInteger || 3 function ( value ) { 4 return typeof value === "number" && isFinite ( value ) && Math . floor ( value ) === value ; 5 } ;

So guess what? Yes, Number.isFinite is also not supported in IE!

source: https://knowyourmeme.com/memes/ah-shit-here-we-go-again

1 if ( Number . isFinite === undefined ) 2 Number . isFinite = function ( value ) { 3 return typeof value === "number" && isFinite ( value ) ; 4 } ;

You maybe think that's it, he finished with polyfilling madness. I thought the same, I don't blame you. Do you remember the original method that I was desperately trying to polyfill?

1 Number . isSafeInteger = 2 Number . isSafeInteger || 3 function ( value ) { 4 return Number . isInteger ( value ) && Math . abs ( value ) <= Number . MAX_SAFE_INTEGER ; 5 } ;

It happens that Number.MAX_SAFE_INTEGER is also not supported on IE, so I had to polyfill that as well.

1 if ( ! Number . MAX_SAFE_INTEGER ) { 2 Number . MAX_SAFE_INTEGER = 9007199254740991 ; 3 }

Lessons

Whenever you spot unconventional/non-frequently-used methods in your code reviews, scream to the world that your peer might be breaking something, ask them to consult the documentation for browser compatibility. Don't blindly trust MDN web docs Polyfill sections. Unfortunately, they don't warn you about whether or not the implementation of the polyfill needs to be polyfilled itself.

If you liked this article, consider sharing (tweeting) it to your followers.