If you're like me, chances are you heard the word polyfill used before in a context where it wasn't easy to deduce a meaning. Thanks to my new tendency of writing down things I'd like to learn about and a subsequent discussion with @tryggvigy , I was able to get a better understanding of what polyfills are.
New features are never supported on all browsers out of the box. Imagine wanting to refactor your code to use new ES2019 features such as the nullish coalescing operator or
Let's take a closer look with the example code from MDN's page on the nullish coalescing operator:
const foo = null ?? 'default string'; console.log(foo); // expected output: "default string" const baz = 0 ?? 42; console.log(baz); // expected output: 0
Now let's try running it on Safari 13.0 (currently not supported):
SyntaxError: Unexpected token '?'
At the time of writing, the
?? operator is supported for 77.08% of global users. If you're using it in production, you're ignoring a very big slice of potential users. To work around this, you can search for a
?? polyfill and add it to your code so that the new syntax will work with supported browsers, and the polyfill will work for the older unsupported browsers.
With Babel installed in our codebase, we can write this:
var foo = object.foo ?? "default";
and have it automatically be converted to:
var _object$foo; var foo = (_object$foo = object.foo) !== null && _object$foo !== void 0 ? _object$foo : "default";
Another interesting example is the polyfill for
Array.prototype.map which can be found here.
To end with, it's worth mentioning that using polyfills exclusively, as opposed to browsers and environments working to natively support new features, is not a good idea for performance and functionality reasons.
Thank you for reading. Until next time 👋
Cover photo by T.H. Chia on Unsplash
Top comments (0)