Don't add or change methods in built-in JavaScript objects

·

2 min read

It is possible to add and modify properties and methods to JavaScript classes and prototypes using the prototype property of the class or constructor function.

class Dog {
    bark() {
        return "Woof!";
    }
}

// Add a new method to the Dog class
Dog.prototype.howl = function() {
    return "Ooowhooooooo!!!";
};

Even though it is possible to use this to add more properties or methods to built-in objects (i.e. Array, String, etc.), it's generally a bad idea to do it.

The problem is, when you make changes to a native object, you could cause weird bugs across the entire codebase, even in external libraries that your project uses.

When you add a new method to a native object, there is the chance of name collisions: a native method with the same name might be added in the future.

Those kinds of errors are very hard to find, especially if the developer who found the bug is not the one who changed the native object. They might assume that built-in objects were never modified (which if often the case) and they would take hours trying to debug.

As I've read on other websites: built-in objects aren't your objects, they are everyone's objects. When you make changes to them, you also change everyone's code.

What are the alternatives?

There are a couple of alternatives to modifying built-in objects. If you add a small number of methods, you can simply create a regular function that takes the object instance as an argument.

Another alternative is to create a new class that inherits from the built-in object. For example:

class ShufflableArray extends Array {
    // This method randomizes the elements in an array
    shuffle() {
        const copy = [...this];

        let index = 0;
        while (copy.length > 0) {
            const copyIndex = Math.floor(Math.random() * copy.length);
            this[index] = copy.splice(copyIndex, 1)[0];
            index++;
        }
    }
}

const array = new ShufflableArray(1, 2, 3, 4, 5);
array.shuffle();
console.log(array); // Outputs [4, 1, 3, 5, 2]

Become a Better JavaScript Developer! Easy, actionable steps to level up your JavaScript skills, right to your inbox. Click here to subscribe