Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Prototypes

Why in MDN functions polyfills use "if (!Array.prototype.filter)" ?

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';

    var t = Object(this);
    var len = t.length >>> 0;    
    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];

        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }

    return res;
  };
}

What do you need to use it?

like image 387
Murad Sofiyev Avatar asked Jan 01 '26 15:01

Murad Sofiyev


1 Answers

That's how they check to see if the thing they're polyfilling is already present.

To use that specific example: Array.prototype refers to the object that is the prototype of all arrays. So Array.prototype.filter is the property that arrays inherit that provides the filter method. By doing if (!Array.prototype.filter), the code checks to see if that property already exists with a truthy value (a function reference is truthy) and doesn't try to add it if it's present. Reading the value of Array.prototype.filter will yield undefined (a falsy value) if filter isn't present on Array.prototype, which tells the code it needs to add the polyfill.

like image 70
T.J. Crowder Avatar answered Jan 05 '26 22:01

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!