Languages
[Edit]
EN

What is Polyfill in JavaScript with code example

3 points
Created by:
Kenya-Spears
860

In this post, we would like to explain what is Polyfill in web development with a simple practical JavaScript example. 

What is Polyfill in JavaScript - Image intro
What is Polyfill in JavaScript - Image intro

2. Definition of Polyfill in Web Development

Edit

We can see the definition of Polifill on Wikipedia:
In web development, a polyfill is a code that implements a feature on web browsers that do not support the feature. Most often, it refers to a JavaScript library that implements an HTML5 web standard.

So in short - polyfill is code that allow us programmers to use new API in older browsers. Usually we use some library that add missing functionality or we can implement
missing methods by ourselves.

For example, we can take JavaScript String API - method includes. The string includes method was added to the ECMA Script 2015 and Internet Explorer doesn't support it.

Let's check Mozilla documentation of String includes method. And from this documentation, we see that Internet Explorer is the only browser that doesn't support this method.

3. Practical explanation with code

Edit

I prepared 2 code examples.

3.1 Example 1 - without a polyfill

Edit

In the first code example, we use the String includes method provided by our browser. In my case I use chrome and this example works great. When we open this example with Internet Explorer we get an error.

Filename: polyfill_explain_v1.html

Console output from Chrome, Firefox, and other browsers:

Console output from Internet Explorer 11 (Default under Windows 10):

SCRIPT438: Object doesn't support property or method 'includes' polyfill_explain.html (9,5)
Screenshot from IE 11 - Object doesn't support property or method 'includes' 

3.2 Example 2 - with polyfill

Edit

At this moment we will go to the second example where we have implemented String includes a method for browsers that don't support this method. In this second example we polyfill String.prototype.includes method and browsers which don't support this method will enter the code and add includes functionality to the String.

Filename: polyfill_explain_v2.html

Console output from Chrome, Firefox, and other browsers:

Console output from Internet Explorer 11 (Default under Windows 10):

4. Video tutorial

Edit

References

Edit
  1. Polyfill (programming) - wikipedia
  2. String.prototype.includes() - Browser Compatibility - Mozilla Docs
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join