JavaScript Polyfills Explained: A Practical Guide for Cracking Frontend Interview

Ronak MathurRonak Mathur
5 min read

But before jumping into implementing polyfills, we need to understand:

  • What is a polyfill?

  • Why developers still use polyfills and their purpose.

Polyfills

Many older browsers do not natively support modern JavaScript functionalities. Polyfills are essential tools that allow developers to bring modern JavaScript features to older browsers, ensuring compatibility and consistency across all users.

Many modern javascript array methods like map(), filter(), forEach(), reduce(), we commonly use in our daily coding. However, legacy browsers (like Internet Explorer), you might find they don't exist natively.

But wait, before we start writing polyfills, it’s important to understand where these methods are defined.
They’re not on the Array constructor itself, but on Array.prototype. This is how all array instances in JavaScript inherit these methods through the prototype chain.

Try logging this in your console:

console.log(Array.prototype)

In your console or terminal, you will see a collection of methods such as map, filter, and reduce, among others, because they are all part of the Array.prototype.

Prototype explanation is beyond the scope of this blog, but it’s important to know that methods like map() are defined on Array.prototype, not directly on the Array object. This allows all arrays to access them through JavaScript’s prototype chain.

Please read more about Prototype on MDN docs https://developer.mozilla.org/en-US/docs/Web/JavaScript

That’s all we need to know for now—let’s move on and build your first polyfill.

Polyfill of Map

The map() method of array it return a new array by applying callback function to each element of a given array.

//syntax
map(callback(currentItem, index, array), thisArg); 
// index is Optional
// array is Optional
// thisArg is Optional

//example
const numbers = [1, 4, 9];
const roots = numbers.map((num) => Math.sqrt(num));  // Output -> [1, 2, 9]

Writing polyfill of map

Array.prototype.myMap = function (cb) {
    // we console.log(this) just to check what this refers to...
    // here this --> is actually array
    console.log("this ", this) // it console log actual array
    let temp = [];
    // to check if callback function is defined or not
    if (typeof cb !== "function") {
        throw new TypeError("Callback function is not a function")
    }

    // to check for both null and undefined
    if (this == null) {
        throw new Error("array is null or undefined");
    }

    for (let i = 0; i < this.length; i++) {
        temp.push(cb(this[i], i, this))
    }
    return temp;
}

//use case
const arr = [1, 2, 3];
const res = arr.myMap((value) => {
    return value * 2
})
console.log(res) // Output [2,4,6]

Polyfill for forEach

The forEach() method iterate over the each item of given array and it return undefined. The typical use case is to execute side effects at the end of a chain

//syntax 
forEach(callback(element, index, array), thisArg*);
// index is Optional
// array is Optional
// thisArg is Optional

//example
const arr = [10, 20, 30];
arr.myForEach((value, index, array) => {
    console.log(`Index ${index}: Value ${value}`);
});

// Output
// Index 0: Value 10
// Index 1: Value 20
// Index 2: Value 30
Array.prototype.myForEach = function (cb) {

    if(this.length === undefined) {
        throw new Error("Array is undefined");
    }

    if(typeof cb !== "function") {
        throw new TypeError("Callback function is not of type function");
    }

    for(let i = 0; i < this.length; i++) {
       cb(this[i], i, this);
    }
}

Polyfill of filter

The filter() method that creates a new array containing all elements from the original array that satisfy a provided test function and return true for all those item pass test condition. It does not modify the original array.

//syntax
filter(function(item, index, array), thisArg*); 
// index is Optional
// array is Optional
// thisArg is Optional

//example
const numbers = [1, 2, 3, 4, 5, 6];

// Filter for even numbers
const evenNumbers = numbers.filter(function(number) {
  return number % 2 === 0;
}); 

// o/p - [2,4,6]
Array.prototype.myFilter = function (cb) {
    if (this === null) {
        throw new Error("array is null or undefined");
    }
    let temp = [];
    for (let i = 0; i < this.length; i++) {
        if (cb(this[i], i, this)) {
            temp.push(this[i])
        }
    }
    return temp;
}

const arr = [2, 4, 5];
const res = arr.myFilter((value) => {
    return value % 2 === 0;
})
console.log(res) // o/p [2,4]

Polyfill of reduce

The reduce() method executes a callback function on each element of the array, resulting in a single output value.

Array.prototype.myReduce = function (cb, initialValue) {
    let accumulator = initialValue || undefined;
    if (this.length === 0) {
        return undefined;
    }

    if (typeof cb !== "function") {
        throw new TypeError("Callback function is not defined ");
    }

    // iterating over each items of this array and accumlating 
    for (let num of this) {
        if (!accumulator) {
            accumulator = num;
        }
        else {
            accumulator = cb(accumulator, num, this)
        }
    }
    return accumulator;
}

const arr = [2,4,5,6];
const res = arr.myReduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log("res ", res)

Polyfills might seem a bit daunting at first, but as you've seen, they're just smart tricks to make modern features work in older environments.

The best part? Writing them helps you really understand how JavaScript works, especially with prototypes and arrays.

That's it! We've just covered some of the most commonly asked polyfill methods for arrays in frontend interviews. We'll add more polyfills for array methods in this blog soon.

Happy Coding
Stay Tune 😊

0
Subscribe to my newsletter

Read articles from Ronak Mathur directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ronak Mathur
Ronak Mathur