liveBook · Manning

Polyfill

As explained in Secrets of the JavaScript Ninja, Second Edition

A polyfill is code that implements a feature in environments that do not natively support it, emulating the missing behavior.

A polyfill supplies a browser feature that is missing, letting code use the standard API where native support is absent. Check for native support first and leave it untouched when available. section 14.3.2 section 14.3

Listing 14.2. A polyfill for the Array.prototype.find method
if (!Array.prototype.find) {                                       #A
  Array.prototype.find = function(predicate) {                     #B
    if (this === null) {
      throw new TypeError('find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;                                #C
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {                             #D
      value = list[i];                                             #D
      if (predicate.call(thisArg, value, i, list)) {               #D
        return value;                                              #D
      }                                                            #D
    }                                                              #D
    return undefined;
  };
}

This Array.prototype.find polyfill checks for native support, then loops through the array and returns the first value accepted by the predicate. section 14.3.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Works through feature detection and an Array.prototype.find implementation, including predicate checks and array iteration.
Examples
Demonstrates an Array.prototype.find polyfill that checks for native support and searches array values with a predicate.
What you can do after
Build a fallback implementation for Array.prototype.find when a browser lacks native support.
How it connects
Links polyfills with feature detection, cross-browser compatibility, ES6, and Array.prototype.find.

Also explained in

Compare how 2 books explain polyfill →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.