What are Polyfills and Transpilers, to understand this let's see why were they introduced and what problem do they solve.
JavaScript language is constantly evolving, there are new features that are being added to it every year. The body behind this i.e ECMA (European Computer Manufacturers Association Script) manages and decides what new features to add/ implement because the more recent features will help us developers, and make our job easy. But the problem is there are some old engines that don't understand this modern code.
Then we have Polyfill and Transpilers to the rescue
Transpiler
Converts Source code from one higher-level language to another higher-level language, so it reads and understands the modern code and rewrites it into older syntax so that it will work in older engines as well. for example:
- TypeScript, after transpiled, is turned into JavaScript.
Babel converts ES6 JavaScript code into ES5 JavaScript code
It is also known as Source to Source Compiler.
“Nullish coalescing operator” ?? was introduced in 2020 before that if you use it in any outdated browsers, it will fail to understand the code what is happening
number= number ?? 6
The transpiler will rewrite the code into
// before running the transpiler
number= number?? 6
// after running the transpiler
number= (number!== undefined && number!== null) ? number: 6;
now this rewritten code will work in older JavaScript engines as well.
Babel is one of the most prominent Transpilers out there
Polyfill
as the name suggest poly - means many and fill - means add,
According to MDN
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.
In simple words: So it is a script that updates/add new functions is called polyfill, It fills in the gap and adds missing implementations
There might be some features that might not support specific browsers, as we are talking about new functions, not the syntax changes so there is no need to transpile anything here. we just have to declare the missing function.
let's take an example of forEach so it supports in all browsers so there is no need to polyfill it, to understand polyfill let's write our own polyfill for it.
const arr = [1,2,3,4,5]
//simulating the browser incompatibility
Array.prototype.forEach = null;
//check for compatibility first
if(!Array.prototype.forEach){
//write your polyfil
Array.prototype.forEach = function(callbackFun){
for(val of this){
calbackFun(val)
}
}
}
arr.forEach((val) => console.log(val*2))
// output : 2,4,6,8,10
we have created our very own polyfill for arr.forEach
Summary:
Transpiler - if using modern syntax or operator
Polyfill - to add functions that may be missing
Thank you for reading