Learnitweb

What is a Polyfill?

A polyfill is a piece of JavaScript code that adds support for modern features in older browsers that do not natively support them. It “fills the gap” by mimicking missing functionality.

Why Do We Need Polyfills?

Older browsers (like Internet Explorer) do not support modern JavaScript features. Polyfills ensure compatibility so that newer features can work in all environments.

Example Problem (Without Polyfill)

Older browsers don’t support Array.prototype.includes(), which was introduced in ES6 (2015).

const fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana"));  // ✅ Works in modern browsers

This will break in Internet Explorer, which does not support includes().

Example of a Polyfill

To make includes() work in older browsers, we can define a polyfill:

if (!Array.prototype.includes) {
  Array.prototype.includes = function (searchElement) {
    return this.indexOf(searchElement) !== -1;
  };
}

Now, fruits.includes("banana") will work even in older browsers.

How to Use Polyfills?

Manually Adding a Polyfill

You can write your own polyfill (like the includes() example above).

Using a Library (Recommended)

Libraries like core-js provide a collection of polyfills:

npm install core-js

Then, import the necessary polyfill:

import "core-js/stable";

Using a CDN

You can include polyfills via a CDN for older browsers:

<script src="https://polyfill.io/v3/polyfill.min.js"></script>

Why Do We Need Polyfills in React?

React uses modern JavaScript features (ES6+ and beyond), but older browsers (like IE11) do not support them. Some common missing features include:

  • Promise (used in async operations)
  • fetch() (used for API calls)
  • Array.includes()
  • Object.assign()

Without polyfills, a React app might break in older browsers.

If you are using Create React App, Facebook provides a built-in polyfill package.

Example: Adding Polyfills for fetch() and Promise

Older browsers don’t support fetch(), so let’s add a polyfill.

Without Polyfill (Will Break in Old Browsers)

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data));

With Polyfill

import "whatwg-fetch";  // Fetch polyfill for older browsers
import "core-js/stable";  // Ensures Promise support

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data));