How to use polyfill in JavaScript?


The developers of JavaScript always keep adding new features to the JavaScript language to improve performance and add better functionalities. Sometimes, it happens that new features don’t support by the old browser versions.

For example, the exponential operator is introduced in ES7, and the trailing comma in the object is also valid in ES7. Now, while developing the application, we have added used the exponential operator in the application. It will work with the newer versions of the browser, but if someone is using a very old version of the browser, they can get errors like the exponential operator is not supported by the browser engine.

So, we can use the polyfill to avoid this kind of error. Let’s understand the meaning of polyfill word by breaking it down into two parts. Poly means many, and fill means filling the gap. It means filling the gap of features in the browser with many techniques if the browser doesn’t support the default features of JavaScript.

There can be two ways to solve the problem of features not being supported by the browser. One is polyfill, and another is transpiler. The transpiler converts the code into the lower version so the browser can support it. For example, we can write code in the ES7 version of JavaScript and use a transpiler to convert it into the ES6 or ES5 to make it supported by older browsers.

Here, we will learn different examples of using the polyfill concept.

Syntax

Users can follow the syntax below to use the polyfill concept to implement JavaScript methods manually.

String.prototype.method_name = function (params) {
   
   // implement the code for the method
   
   // use this keyword to access the reference object
}

We have added the method to the string prototype in the above syntax. The method_name suggests the method name. We assigned the function taking multiple parameters to the method.

Example 1 (Includes() method without polyfill)

In the example below, we have used the String object's built-in includes() method. We have defined the string and used the includes() method to check whether the string contains a particular word or substring.

<html>
<body>
   <h2>Using the <i>includes() method without polyfill </i> in JavaScript</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      let str = "You are welcome on TutorialsPoint's website. Hello users! How are you?";
      let isWelcome = str.includes('welcome');
      content.innerHTML += "The original string: " + str + "<br>";
      content.innerHTML += "The string includes welcome word? " + isWelcome + "<br>";
      let isJavaScript = str.includes('javaScript');
      content.innerHTML += "The string includes JavaScript word? " + isJavaScript + "<br>";
   </script>
</body>
</html>

Example 2 (Includes() method with polyfill)

In the above example, we used the built-in includes() method. In this example, we will define the polyfill for the includes() method. If any browser doesn’t support the includes() method, it will execute the user-defined includes() method.

Here, we have added the includes() method to the prototype of the string object. In the function, we throw the error if the search string is a type of regular expression. Also, the ‘pos’ parameter is an option, so if the user doesn’t pass it, consider it zero. At last, use the indexof() method to check whether a string contains the word, and return a Boolean value based on that.

<html>
<body>
   <h2>Using the <i>includes() method with polyfill </i> in JavaScript</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      String.prototype.includes = function (str, pos) {
         
         // first, check whether the first argument is a regular expression
         if (str instanceof RegExp) {
            throw Error("Search string can't be an instance of regular expression");
         }
         
         // second parameter is optional. So, if it isn't passed as an argument, consider it zero
         if (pos === undefined) {
            pos = 0;
         }
         content.innerHTML += "The user-defined includes method is invoked! <br>"
         
         // check if the index of the string is greater than -1. If yes, string includes the search string.
         return this.indexOf(str, pos) !== -1;
      };
      let str = "This is a testing string. Use this string to test includes method.";
      content.innerHTML += `The original string is "` + str +`" <br>`;
      let isTesting = str.includes('testing');
      content.innerHTML += "The string includes testing word? " + isTesting + "<br>";
      let isYour = str.includes('your');
      content.innerHTML += "The string includes your word? " + isYour + "<br>";
   </script>
</body>
</html>

Example 3 (Implementing the polyfill for the filter() method)

We have implemented the polyfill for the filter() method in the example below. We first ensure that the reference array is not null and callback is a type of function. After that, we iterate through the array and execute the callback function for every array value. If the callback function returns true, we push it to the output array. At last, we return the output array containing the filtered values

<html>
<body>
   <h2>Using the <i> filter() method with polyfill </i> in JavaScript</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      Array.prototype.filter = function (callback) {
         
         // check if the reference array is not null
         if (this === null) throw new Error;
         
         // check that callback is a type of function
         if (typeof callback !== "function") throw new Error;
         var output = [];
         
         // iterate through array
         for (var k = 0; k < this.length; k++) {
            
            // get value from index k
            var val = this[k];
            
            // call the callback function and, based on a returned boolean value, push the array value in the output array
            if (callback.call(this, val, k)) {
               output.push(val);
            }
         }
         return output;
      };
      function getDivisibleBy10(val, k) {
         
         // return true if val is divisible by 10.
         if (val % 10 == 0) {
            return true;
         }
         return false;
      }
      let array = [10, 20, 40, 65, 76, 87, 90, 80, 76, 54, 32, 23, 65, 60];
      let filtered = array.filter(getDivisibleBy10); 
      content.innerHTML += "The original array is " + JSON.stringify(array) + "<br>";
      content.innerHTML += "The filtered array is " + JSON.stringify(filtered) + "<br>";
   </script>
</body>
</html>

This tutorial taught us to implement the polyfill for the includes() and filter() methods. However, users can use the if-else statement to check whether the browser supports the particular method. If not, execute the user-define method, otherwise built-in method.

Updated on: 01-Mar-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements