15

I've read a few articles that suggest extending the built-in objects in JavaScript is a bad idea. Say for example I add a first function to Array...

Array.prototype.first = function(fn) {
    return this.filter(fn)[0];
};

Great, so now I can get the first element based on a predicate. But what happens when ECMAScript-20xx decides to add first to the spec, and implement it differently? - well, all of a sudden, my code assumes a non-standard implementation, developers lose faith, etc.

So then I decide to create my own type...

var Enumerable = (function () {
    function Enumerable(array) {
        this.array = array;
    }
    Enumerable.prototype.first = function (fn) {
        return this.array.filter(fn)[0];
    };
    return Enumerable;
}());

So now, I can pass an array into a new Enumerable, and call first on the Enumerable instance instead. Great! I've respected the ECMAScript-20xx spec, and I can still do what I want it to do.

Then the ES20XX+1 spec is released which introduces an Enumerable type, which doesn't even have a first method. What happens now?

The crux of this article boils down to this; Just how bad is it to extend the built in types, and how can we avoid implementation collisions in future?

Note: The use of namespaces might be one way to deal with this, but then again, it isn't!

var Collection = {
    Enumerable: function () { ... }
};

What happens when the ECMAScript spec introduces Collection?

5

6 Answers 6

14

This is precisely the reason why you must try to pollute the global namespace as little as possible. The only way to completely avoid any sort of clashes is by defining everything within an IIFE:

(function () {
    let Collection = ...
})();

If and only if you need to define global objects, for instance because you're a library and you want to be used by 3rd parties, you should define a name which is extremely unlikely to clash, for instance because it's your company name:

new google.maps.Map(...)

Any time you define a global object, which includes new methods on existing types, you're running the risk of some other library or some future ECMAScript standard trying to co-opt the name sometime in the future.

6

The issue with the first approach is that you extend the prototype for all scripts on your page.

If you were to include a third-party script which relies on the new, native ES-20xx Array.prototype.first method, then you would break it with your code.

The second example is only really a problem, if you were to use global variables (which I hope you are not doing…). Then the same problem could happen.

The thing is, spec authors are increasingly wary of not destroying the existing web, so they have to rename future features if too many existing sites break. (And this is also why you should not create polyfills for web platform specs which are not yet finalized, BTW)

The issue is certainly bigger if you create a library or a framework that extends native objects and is used by 100s or 1000nds of websites. That's when you start hindering the standards process.

If you use your variables within a function or a block scope, and you don't rely on future features, you should be just fine.

Function scope example:

(function() {
  var Enumerable = {};
})();

Block scope example:

{
    const Enumerable = {};
}
3

The danger here is much more subtle than colliding with a future ES20xx standard. At least there you can delete your own code and deal with the fallout of any potential behavioral differences.

The danger is that you, and someone else, both decide to extend the built-in type with inconsistent behavior.

Consider something like this

// In my team's codebase
// Empty strings are empty
String.prototype.isEmpty = function() { return this.length === 0; }

// In my partner team's codebase
// Strings consisting any non-whitespace chars are non-empty
String.prototype.isEmpty = function() { return this.trim().length === 0; }

You have two equally valid definitions of isEmpty and the last one in wins. Imagine the pain you're going to have a year down the road when your unit tests pass, your partner team's unit tests pass, but you can't merge your codebases in a single webpage without getting really weird crashes depending on whose library gets loaded last. That is a maintainability nightmare.

Then you get to get in a room with your partner team and argue for six hours about whose definition of isEmpty is "correct", an arbitrary decision will be made, and one of the two of you get to look at every single instance of isEmpty in your codebase to determine how to make it work with the new function. And you'll probably introduce some new bugs in the process.

Then repeat this whole process again when you discover that you both wanted a toInteger function on numbers but didn't think to hold a company-wide meeting on what to do with negative numbers

// -3.1 --> -4    
Number.prototype.toInteger = function() { return Math.floor(this); }

// -3.1 --> -3    
Number.prototype.toInteger = function() { return Math.trunc(this); }
2

WARNING: Opinionated answer.

I don't believe extending JavaScript objects is "evil". Obviously there are dangers and you need to be aware of those (as you clearly are). My only caveat to that statement is that if you do, you must introduce a method of alerting yourself to conflicts.

In other words, rather than simply defining a first function on the array prototype, you should first see if Array.prototype.first is defined and if it is, then throw (or alert yourself to this conflict in some other way). Only if it's not defined should you allow your code to define it or you'll replace the definition for everyone.

1
  • 1
    The tool (extending Javascript objects) is by definition morally neutral. Kudos for pointing it out. Oct 31, 2016 at 17:28
1

As an alternative to all the amazing answers that were presented, you can do the same that polyfills do.

Usually, when someone writes something that messes with prototypes, one checks if a value is already defined.

Here's an example:

if(!Array.prototype.first) {
    Array.prototype.first = function(fn) {
        return this.filter(fn)[0];
    };
}

This is fine for tiny pieces of code, but may give problems on large libraries.
Implementing an anonymous self-calling function can help with this, like so:

(function(){
    // Leave if it is already defined
    if(Array.prototype.first) {
        return;
    }

    Array.prototype.first = function(fn) {
        return this.filter(fn)[0];
    };
})();

This has the benefict of all the solutions provided before.

If you want to reduce the footprint of the downloaded code, one could load dynamically the needed scripts required.
If a new Enumerable is created, you can use the one that the browser has, or your own if there's none.
This is extremelly dependent on your codebase.

2
  • However, there is no standard first method, so you cannot polyfill it, and the approach of overwriting it only when it doesn't exist does not work if it does later get standardized to something different.
    – Bergi
    Nov 1, 2016 at 18:09
  • @Bergi That is a downside :/ But with an half decent toolkit (the browser console), you could try to trace back all the errors that are happening. Depending on how huge the code is, this can be found with moderate difficulty. Nov 1, 2016 at 18:24
-1

This question and these answers seem very ECMA5 oriented, instead of 6. The use of prototypes is pretty useless when ECMA6 brought classes with it. There are not many huge reasons not to add to the prototype of a built-in, but mostly it's more a case of, 'if you can avoid it, you should'.

First off, you may break older browsers when adding to a built-in type, also you may break the 'for(i in array)' format, because of how for...in is called on a basic level, it may have unexpected results.

The main reason in my opinion, is that there is a very good alternative in ECMA6, which is subclassing. Instead of using any prototype, just use this:

class myArray extends array {
    constructor() { ... }

    getFirst() {
        return this[0];
    }

    // Or make a getter

    get first() { 
        return this[0]; 
    }
}

You can put whatever function you need in the getter, but it still is independent code that doesn't intrude on future namespaces. But, because you're sub-classing, you don't have to rewrite an array. So, it's less that it's pure evil, but more of it's better coding to not do it, much in the same way that it isn't necessarily evil to write all your javascript in one long page, but if you can avoid it, it is better standard practice.

6
  • JavaScript was always an OO language, and inheritance has always been possible. ES6 classes are merely nicer syntax on top of it.
    – deceze
    Oct 31, 2016 at 17:45
  • Right... So the downvote is because the alternative is irrelevant? The extending is the point of my answer. Every answer is about prototyping, as is the question, and my response is that they built nice syntax so that you can extend the built-in type without ruining it. Oct 31, 2016 at 17:54
  • 1
    How is this myArray class equal to any of OP’s examples? The advantage of OP’s first code example is that you can do [1, 2, 3].first() which is obviously not possible with your code. Also, your answer doesn’t answer the actual question.
    – idmean
    Oct 31, 2016 at 18:11
  • @idmean Right, you would have to do var myArray = new myArray(1,2,3). But after that you can do myArray.first, myArray.push(4), etc. It acts exactly as an Array does except for the initial initialization. Which, btw is EXACTLY what OP did with creating his own var 'Enumeration', except using prototypes. My point, if you had read my answer, was that there are two reasons that are standardly accepted as to why not to do this, which is browser support and for...in support. But my main reason is 'if there is a better way, which there is, then use the better way and avoid any potential pitfalls'. Oct 31, 2016 at 18:16
  • 1
    Just to clarify: my issue is that you're presenting this as if extending classes is something new and exclusive to ES6, when it fact this has always been possible and in fact is still using prototypes under the hood. All ES6 classes do is sugarcoat the syntax, the basic mechanics haven't changed one bit. And you're still prone to name clashes with those extended classes.
    – deceze
    Oct 31, 2016 at 18:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.