Polyfills & Transpilers
Code Quality: Polyfills & Transpilers
Describe what a JavaScript Trans-piler does?
View Answer:
Interview Response: A transpiler is a unique piece of software that can parse ("read and understand") modern code and rewrite it using older syntax constructs so that the result would be the same.
Code Example:
// before running the transpiler
height = height ?? 100;
// after running the transpiler
height = height !== undefined && height !== null ? height : 100;
note
Before 2020, JavaScript did not have a nullish coalescing operator (??). We needed a piece of software to convert it into workable code for older browsers to do work.
What is a Polyfill in JavaScript?
View Answer:
Interview Response: A polyfill fills the gaps where newer JavaScript features may not be compatible with older browsers.
Code Example: Polyfill if Math.trunc function does not exist in an older engine.
if (!Math.trunc) {
// if no such function
// implement it
Math.trunc = function (number) {
// Math.ceil and Math.floor exist even in ancient JavaScript engines
// they are covered later in the tutorial
return number < 0 ? Math.ceil(number) : Math.floor(number);
};
}