Polyfills and Transpilers in JavaScript…30daysofJavaScript ==> Day 26
One of the greatest heights for a web application to attain is simply for it to be able to work on any device as long as it is connected to the internet. This could be very challenging as some of these devices are really old and lack a lot of support and because of the constant evolvement of JavaScript, it is important to use the new features as they come. But wait, new features and old devices!!! A nightmare!!! It will never work!!! I mean, how???
From time to time, syntaxes are reviewed in order to be improved as well as removed if considered unnecessary. The amazing thing about JavaScript as a master of the web is that its evolvement continually tries to accommodate access from old devices and more advanced features in newer devices. So even tho some features might be absent, a good chunk of the code is going to work with ease.
With polyfills and transpilers, we have less to worry about.
Polyfills
Polyfills are scripts known to add new functions/updates to older JavaScript engines. It acts to fill the space and add missing implementations. For example, Math.trunc(n)
is a function that “cuts off” the decimal part of a number, e.g Math.trunc(1.23)
returns 1
. In some (very outdated) JavaScript engines, there’s no Math.trunc
, so such code will fail.
How to get started with polyfills? Interestingly, there are libraries that can be used for this (bonus: frameworks such as react.js and angular help generate them while a new app is created). Examples of these libraries are core js and polyfill.io.
Transpilers
A transpiler is a unique piece of software that translates a source code to another source code. It simply read source codes in modern implementation and translates them to one in older syntax thereby making it easier for the older JavaScript engines to work on.
E.g. JavaScript before the year 2020 didn’t have the “nullish coalescing operator” ??
. So, if a visitor uses an outdated browser, it may fail to understand the code like height = height ?? 100
. A transpiler would analyze our code and rewrite height ?? 100
it into (height !== undefined && height !== null) ? height : 100
.
To get started with transpilers, Babel is a well known prominent transpiler out there.
In summary, support in JavaScript is one of the many advantages for which it is known for.
What is this about?
30daysofjavascript is a series of writing on how I learned to code in JavaScript. These episodes are as simplified as possible and for beginners like me, I hope you find JavaScript less confusing throughout this episode. Thank you as always and see you in the next episode. Check out every episode I have written here.