Change Array.prototype in node.js

Jam*_*een 0 javascript arrays prototypejs node.js

I want to make some functions available to all my arrays.

For instance, I want a function to remove duplicates:

Array.prototype.uniq = function () {
  return Array.from(new Set(this));
};
Run Code Online (Sandbox Code Playgroud)

But I want to make this function work in my entire node.js project.

Will it work if I just put it in server.js which is run when I type npm start?

It would be great if it also works on the client. Is it possible or should I consider server and client strictly separated from one another?

Is it bad practice to extend Array.prototype like this? I just think it seems stupid to write the code many times.

Another options could be to use

function uniquify(arr) {
  return Array.from(new Set(arr));
}
Run Code Online (Sandbox Code Playgroud)

but array.uniq() seems better than uniquify(array).

T.J*_*der 5

First: If you're going to add properties to Array.prototype, don't add them via simple assignment. Doing so creates enumerable properties, and code that relies on arrays not having any enumerable properties by default will break.

So use defineProperty instead:

Object.defineProperty(Array.prototype, "uniq", {
    value: function uniq() {
      return Array.from(new Set(this));
    }
});
Run Code Online (Sandbox Code Playgroud)

To your questions:

Will it work if I just put it in server.js which is run when I type npm start?

I'm not sure what server.js you're talking about, but if you're talking about modifying files that are built-in parts of Node or npm rather than parts of your project, I strongly recommend not doing so.

It would be great if it also works on the client. Is it possible or should I consider server and client strictly separated from one another?

They're completely separate. If you want to do this on the client, you'll need to include script adding uniq on the client.

Is it bad practice to extend Array.prototype like this? I just think it seems stupid to write the code many times.

There are two camps of thought on that:

  1. Yes, it's bad. You're likely to run into naming conflicts with someone else adding their own, different uniq. Combining code from multiple sources is getting very, very common, increasing the odds of those problems. Future versions of the language may add uniq. Since the committee steering the language (TC-39) tries to steer around potential conflicts, if your client-side library became popular, it would make their work harder. (MooTools has, more than once.)

  2. No, it's not bad, it's what prototypes are for. Naming conflicts can be handled if and when. TC-39 can lump it.

You'll have to make your own decision about whether to do it.