polyfills_javascript_forEach_map_filter_reduce

Polyfills and transpilers in Javascript

In this article, we will study polyfill and transpilers in Javascript. In the first part, we will go through the definitions. After that, we will implement polyfills for reduce, map, filter, and foreach. These are critical topics for the interview.

Polyfills in Javascript

Polyfills is a piece of code that uses to provide modern functionality in the older browser that does not support it by default. For example, polyfills can be used to implement the reduce method in the IE7 browser, which does not support these functionalities.

What are Transpilers in Javascript?

Transpilers translate the code to the same language. Compilers translate code from one language to another, for example, Java to Bytecode. Transpilers transform (changes) the code of a language into another version of the same language.

So a Javascript transpiler converts a JS code (ES6 code) to another form of Javascript (ES5 code). These are the popular transpilers:

  1. Typescript
  2. Babel
  3. Traceur

We will see an example of transpilers and how they translate the code. As we know, in ES6 class, functionality is introduced, but in ES5, it does not support the functionality.

In ES6 class has been introduced similarly to the other object-oriented languages. For example:

class School {
  addStudent() {}
  studentAtt() {}
  teacherDetails() {}
  static getStudentMarks() {}
}

As we know that old browsers (IE 7) do not support class for that code, we need to convert it into the ES5 format so that the earlier browser will understand the code. If we try to run this code in that browser, it will throw an incompatibility error. Another way of writing a class code in ES5 is using function and prototype keywords. The class code can be written in ES5 code as follows:

function School() {}

School.prototype.addStudent= function () {};

School.prototype.studentAtt = function () {};


School.prototype.teacherDetails = functions () {};

School.getStudentMarks= function () {};

When the transpiler detects the old browsers that don’t support the class, it will convert the School class to its function version using the function code and output the code result.

Polyfills for forEach()

In this section, we will try to implement polyfills for forEach functionality. The forEach() function executes a function once for each item in an array in order. The return value of the forEach() function is undefined(unknown).

Syntax :

let arrayItems = [1,2,3,4,5,6,7,8,9];

function consoleFunc(x) {
   console.log(x);
}
arrayItems.forEach(consoleFunc);

output: 1 2 3 4 5 6 7 8 9

Polyfills for the forEach

let arrayItems = [1,2,3,4,5,6,7,8,9];

function polyfillsFunc(x) {
   console.log(x);
}

Array.prototype.ourForEach = function (callBack) {
  for (let i = 0; i < this.length; i++) {
    callBack(this[i]);
  }
};
names.ourForEach(polyfillsFunc);


output : 1 2 3 4 5 6 7 8 9

Polyfills for .map

.map() is very much similar to the .forEach() method, except, instead of returning items out of the array, it returns the array itself. Syntax for the map function:

let newArrayFormed = arr.map(callback(currentValue[, index[, array]]) {
  // return element for newArray, after executing something
});

The original Array.map function(method) takes a callback method as an argument, and that callback function has three arguments passed to it

  1. current value (compulsory)
  2. array(optional)
  3. index of the current item (optional)

Let’s see an exampe for .map in which we will take an array and return the array with all items multiplied by the five.

const users = [1, 2, 3, 4, 5];
function fiveTimes(x) {
  return x * 5;
}
const newUsers = users.map(double);
// console
// [1, 10, 15, 20, 25]

Let’s implement the polyfills for the .map:

const arrayItems= [1, 2, 3, 4, 5];

function fiveTimes(x) {
  return x * 5;
}

Array.prototype.ourMap = function (callBack) {
  const returnArray = [];
  for (let i = 0; i < this.length; i++) {
    returnArray .push(callBack(this[i]));
  }
  return returnArray ;
};
console.log(users.ourMap(fiveTimes));

// console
// [1, 10, 15, 20, 25]

Pollyfill for Array.filter()

.filter() decide what kind of items we want in the resulting array. For example, we have information on students with their marks, and we want a student who has a greater percentage than 75%. In that case, .filter can be used.

Syntax for the .filter

let newArray = arr.filter(callback(currentValue[, index[, array]]) {
  // return element for newArray, if true
});

Let’s see an example for the .filter in which we will take an array and return the array with all students with a higher percentage than 75%.

const studentInformation= [
  {
    name: "Bobby Tarantino",
    marksPercentage: 85,
  },
  { name: "John Deo",
    marksPercentage: 65 
  },
  {
    name: "Krishna",
    marksPercentage: 94,
  },
  {
    name: "Madhav",
    marksPercentage: 74,
  },
  { name: "Mike", 
    marksPercentage: 55 
  }
];

function greaterThan75(x) {
  return x.marksPercentage> 75;
}

const filtered = studentInformation.filter(greaterThan75);
console.log(filtered)

// console
// [ 
// {name: "Bobby Tarantino", marksPercentage: 85},
// {name: "Krishna", marksPercentage: 94}
// ]

Let’s implement the polyfills for the .map:

Array.prototype.myFilter = function (callBack) {
  let outputRecords = [];
  for (let i = 0; i < this.length; i++) {
    if (callBack(this[i])) {
      outputRecords .push(this[i]);
    }
  }
  return outputRecords ;
};

function greaterThan75(x) {
  return x.marksPercentage> 75;
}



function greaterThan75(x) {
  return x.marksPercentage> 75;
}

const filtered = studentInformation.myFilter (greaterThan75);
console.log(filtered)

// console
// [ 
// {name: "Bobby Tarantino", marksPercentage: 85},
// {name: "Krishna", marksPercentage: 94}
// ]

Pollyfill for Array.reduce()

reduce() function in Javascript is used to reduce the array to a single value. It’s not an exact definition, but we can say this in simple language.

Syntax for reduce()

array.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])

Array.reduce function accepts two arguments :

  1. callback as an argument. Callback functions can have four arguments.

         a. accumulator (compulsory)

         b. current value (compulsory)

         c. index of the current value(optional)

          d. array(optional)

2. Initial Value

Let’s see an example for the .reduce in which we will take an array and return the sum of the all value exist in the array.

const marks= [91, 58, 78, 88, 59, 69];

function addNumbers(acc, curr) {
  acc= acc + curr;
  return acc;
}

const sumMarks = marks.reduce(addNumbers, 0);

console.log(sumMarks );

//output
443

Let’s implement the polyfills for the .reduce():

const marks= [91, 58, 78, 88, 59, 69];
Array.prototype.newReduce = function (callback, initialVal ) {
  var acc = initialVal === undefined ? undefined : initialVal ;

  for (var i = 0; i < this.length; i++) {
    if (acc !== undefined) {
      acc = callback.call(undefined, acc , this[i], i, this);
    } else {
      acc = this[i];
    }
  }
  return acc ;
};


function addNumbers(acc, curr) {
  acc= acc + curr;
  return acc;
}

console.log(numbers.newReduce(addNumbers));

// console
// 443

I hope you have found this useful. Thank you for reading.

1 thought on “Polyfills and transpilers in Javascript”

Comments are closed.