Murad Sofiyev Murad Sofiyev - 2 years ago 304
Javascript Question

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 (, val, i, t)) {

return res;

What do you need to use it?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download