What are JavaScript polyfills for?

Answer

What Are JavaScript Polyfills?

A polyfill is a piece of code (usually written in JavaScript) that provides modern functionality to older browsers or environments that do not natively support certain features.

Polyfills are used to "fill in" gaps in browser compatibility by emulating missing features so that your code can run consistently across different environments.

Why Are Polyfills Needed?

How Do Polyfills Work?

For example, if the Array.prototype.includes() method is missing in an older browser, a polyfill can add it manually.

Example: Polyfill for Array.prototype.includes()

The includes() method checks whether an array contains a certain value. It was introduced in ES6, but older browsers like Internet Explorer do not support it.

Here’s a polyfill for includes():

if (!Array.prototype.includes) {
  Array.prototype.includes = function (searchElement, fromIndex) {
    if (this == null) throw new TypeError('"this" is null or not defined');
    let array = Object(this);
    let length = array.length >>> 0;
    if (length === 0) return false;

    let startIndex = fromIndex || 0;
    let k = Math.max(
      startIndex >= 0 ? startIndex : length - Math.abs(startIndex),
      0
    );

    while (k < length) {
      if (
        array[k] === searchElement ||
        (Number.isNaN(array[k]) && Number.isNaN(searchElement))
      ) {
        return true;
      }
      k++;
    }
    return false;
  };
}

Common Use Cases for Polyfills

  1. New JavaScript Methods or Features
  1. Browser-Specific Features
  1. HTML5 and CSS3 Features

How Are Polyfills Used?

Example of Loading Polyfills via CDN:

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

Popular Polyfill Libraries

Summary

MDN Web Docs: Polyfills