JavaScript is an ever-evolving language. New features are added to JavaScript every year. When it comes to our browsers they don’t need to always support the latest features. So how to make our modern code work on older engines that don’t understand recent features yet?
There are two tools for that:
1. Transpilers.
2. Polyfills.
1. Transpilers
A transpiler is a special piece of software that translates source code to another source code. It can parse (“read and understand”) modern code and rewrite it using older syntax constructs so that it’ll also work in outdated engines. Babel is a transpiler and let’s see an example of how it works.
Arrow functions are not supported by IE11 and Opera Mini.
[1,2,3,4,5].map((n)=>n*2) // return [2,4,6,8,10]
Babel is a compiler: it takes code written in one standard and transpiles it to code written into another standard. Here Babel will convert it into something like this.
[1,2,3,4,5].map(function(n){
return n*2
}
) // return [2,4,6,8,10]
2. Polyfills
Polyfills are the functions or features that older browsers don’t support and if we don’t write some replacement functions for that the code will throw a run time error. So to tackle this problem we write some replacement code so that everything works fine. In modern-day interviews, most companies are asking us to write polyfills for common JavaScript functionalities.
Here I will list down the most important ones. The ones that are asked more frequently.
2.1 Polyfill for Array. flat()
const arr = [1, 2, 3, 4, 5, [6, 4, 3, 5, [1, 2, 3]]];
function myFlat(arr, depth = 1, output = []) {
if (depth <= 0) {
output.push(arr);
return output;
} else {
for (const item of arr) {
if (Array.isArray(item)) {
myFlat(item, depth - 1, output);
} else output.push(item);
}
}
return output;
}
console.log(myFlat(arr, 10));
2.2 Polyfill for Array.filter()
function myFilter(arr, fn, output = []) {
arr.forEach((element) => {
if (fn(element)) {
output.push(element);
}
});
return output;
}
const isEven = (num) => {
return num % 2 === 0;
};
const arr = [1, 2, 3, 4, 5, 6, 6, 6, 9];
const onlyEvenElements = myFilter(arr, isEven);
console.log(onlyEvenElements);
2.3 Polyfill for Array.reduce()
const add = (acc, curr) => {
return acc + curr;
};
function myReduce(arr, callBack, init = 0) {
let res = init;
arr.forEach((item) => {
res = callBack(res, item);
});
return res;
}
const arr = [1, 2, 3, 4, 5];
console.log(myReduce(arr, add, 0));
2.4 Polyfill for Array.map()
function doubleVals(item) {
return item * 2;
}
const arr = [1, 2, 3, 4, 5];
Array.prototype.myMap = function (callback) {
let result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i]));
}
return result;
};
console.log(arr.myMap(doubleVals));
2.5 Polyfill for Array.forEach()
const arr = [1, 3, 4, 5, 5, 6];
const logger = (item, index) => {
console.log(item, index);
};
Array.prototype.forEach = function (callBack) {
for (let i = 0; i < this.length; i++) {
callBack(this[i], i);
}
};
arr.forEach(logger);
2.6 Polyfill for Promise.all()
let promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("resolved 1");
}, 3000);
});
let promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("resolved 2");
}, 3000);
});
let promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("resolved 3");
}, 3000);
});
let promise4 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("resolved 4");
}, 3000);
});
const arr = [promise1, promise2, promise3, promise4];
function myAll(promises) {
const output = [];
let promisesResolved = 0;
return new Promise((resolve, reject) => {
try {
promises.forEach(async (promise, index) => {
const response = await promise;
promisesResolved += 1;
output.push(response);
if (promisesResolved === promises.length) {
resolve(output);
}
});
} catch (error) {
reject(error);
}
});
}
myAll(arr).then((res) => {
console.log(res);
});
2.7 Polyfill for Function.bind()
Function.prototype.myBind = function(...args){
var callback = this,
ctx = args.splice(1);
return function(...a){
callback.call(args[0], ...[...ctx, ...a]);
}
}
const result2 = printName.myBind(myName, "Palia",);
result2("India");
So, these are the important polyfills that come across my mind when I think about the most important polyfills that are asked in interviews.
If you understood anything I said here please give a clap reaction and follow me because it helps me to stay motivated and take out time from my schedule to write these articles. It will not cost you anything but will help me a lot