~/

Back

Browser polyfill madness, Mozilla and IE

#javascript
Posted on 20, Jul, 2019

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

What is a polyfill?

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.

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!“.

Number.isSafeInteger =
Number.isSafeInteger ||
function (value) {
return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER
}

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.

Number.isInteger =
Number.isInteger ||
function (value) {
return typeof value === 'number' && isFinite(value) && Math.floor(value) === value
}

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



if (Number.isFinite === undefined)
Number.isFinite = function (value) {
return typeof value === 'number' && isFinite(value)
}

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?

Number.isSafeInteger =
Number.isSafeInteger ||
function (value) {
return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER
}

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

if (!Number.MAX_SAFE_INTEGER) {
Number.MAX_SAFE_INTEGER = 9007199254740991 // Math.pow(2, 53) - 1;
}

»Lessons

  1. 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.
  2. 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.
Last modified on 12, Oct, 2024